2011-03-24 57 views
0

如果我写了两个构造这样的下面:构造问题在javascript

Person(name, age) { 
    this.name = name; 
    this.age = age; 
    sayName = function() { 
     alert("hello"); 
    }; 
} 

Person(name, age) { 
    this.name = name; 
    this.age = age; 
    this.sayName = function() { 
     alert("hello"); 
    }; 
} 

的区别是什么?是否

sayName

真的是第一个代码的东西吗?它有用吗?

+0

当你问有关书籍的问题,请有关工作的信息。它可以帮助人们帮助你,并正确地归属代码。在这种情况下,该示例来自Nicholas C. Zakas(Wrox,2009)的专业JavaScript for Web Developers第二版*第152页。 – Dori 2011-03-31 00:33:50

回答

-1

sayName第一个代码是 私有 全局函数,而在第二个它是一个特权公共函数。


更新#1:

下面的代码几乎概括了他们的意思

function Person(name, age) { 
    this.name = name; 
    this.age = age; 
    sayName = function() { //define in global name-space 
    alert("hello"); 
    } 

    var sayNamePvt = function() { //private function 
     alert("hello pvt"); 
    } 

    this.callPvt = function(){ //shows how privilege function can access private vars and functions 
     sayNamePvt(); 
    } 
} 


function Person1(name, age) { 
    this.name = name; 
    this.age = age; 
    this.sayName = function() { //privilege public function 
     alert("hello1"); 
    } 
} 


var one = new Person('abc', 12); 
var two = new Person1('abcd', 11); 
two.sayName();//privileged public access 
sayName(); //global access 
//one.sayName(); //ERROR: one.sayName is not a function 
//one.sayNamePvt(); //ERROR: one.sayNamePvt is not a function 
one.callPvt(); //privileged method can call private functions 
+2

实际上,因为没有var关键字,所以它是全局函数 – qwertymk 2011-03-24 03:25:48

+0

@qwertymk woops。错过了细线。 – Nishant 2011-03-24 03:42:54

+0

@jsnewman更新了答案,并为之前的混乱答案道歉。 – Nishant 2011-03-24 03:57:12