2016-08-04 163 views
1

我不明白爲什麼警報(John.hasOwnProperty('firstName'));返回true,而firstName不是在實例John中定義在Person prototype中?javascript hasOwnProperty返回true而不是false?

https://jsfiddle.net/xfdnsg2w/

Person = function(firstName, lastName) { 

     this.firstName = firstName; 
     this.lastName = lastName; 

    } 

    var John = new Person("John"); 
    alert(John.hasOwnProperty('toString')); 
    alert(John.hasOwnProperty('firstName')); 
+3

如果你在'Person.prototype'上定義它,你將會把它分配給'Person.prototype.firstName'。諸如'firstName'和'lastName'之類的屬性通常以您擁有的方式定義,並且是特定於實例的(由對象本身擁有,而不是原型鏈)。 –

回答

4

在你的代碼中的 「名字」 屬性在人物原型定義。它在構造函數中作爲「自己」屬性初始化。

即使原型上有「firstName」和「lastName」屬性,只要您在構造函數中爲它們賦值,它們就會變成「自己」的屬性。原型屬性通常用作訪問屬性,通常它們具有作爲值的功能。

相關問題