2012-12-22 52 views
0

這個問題的靈感from this article by Yehuda Katz.相關部分ykatz文章是這樣的:困惑於JavaScript構造函數和原型

爲了便於面向對象的編程,JavaScript允許 您使用函數對象的組合使用 新對象與構造函數的原型來調用:

var Person = function(firstName, lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
} 

Person.prototype = { 
    toString: function() { return this.firstName + ' ' + this.lastName; } 
} 

在這裏,我們有一個功能單一的對象,既是一個構造 功能找一個對象用作新對象的原型。

我很困惑,因爲在我看來,作爲構造函數的Function對象和原型是不同的。這是從鉻輸出以下控制檯清楚:

chrome console output

即,構造函數是上面的兩個參數的函數對象:firstName和lastName;而原型只是一個普通的物體,它恰好有一個屬性(toString),而這個屬性又是由單獨的功能對象定義的function() { return this.firstName + ' ' + this.lastName; }

我是誤會他在說什麼,或者文章不正確?

回答

1

是的,這是不正確的。用於新對象的原型是構造函數的.prototype屬性在創建對象時引用的原型,該對象是構造函數中的單獨純對象。

function Person() { 

} 

var a = new Person(); //a.__proto__ is assigned Person.prototype 

Person.prototype = {}; //This doesn't affect a, because .__proto__ was assigned at creation time 

var b = new Person(); //b.__proto__ is assigned Person.prototype, which is just the random object we created with {}