2011-03-24 35 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