2012-12-22 54 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 {}