2014-07-25 56 views
3

每当我重新定义函数的原型并创建它的新对象时,其构造函数就会开始指向根对象函数而不是函数本身。让我用情景解释:对象函数在重新定义自定义函数的原型后指向对象函数

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

Person.prototype.getFullName=function() 
{ 
    return this.firstName+" "+this.lastName; 
} 
var student=new Person("Ankur","Aggarwal"); 
student.constructor //shows Person which is correct 

之后,如果我重新定义了人物原型创造的改变

Person.prototype={} 
var manager=new Person('John','Smith'); 
manager.constructor // Points to Object. Why? 

也是一个新的对象,如果它指向的对象不是人,怎么来的它有权访问像firstName和lastName这样的Person属性?

enter image description here

回答

2

由于构造:

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

它有一个默认的原型属性,它是一个对象,其构造属性引用构造。这个属性(默认情况下)通过[[Prototype]]链继承。

当你创建一个实例,在的firstNamelastName的属性上的实例定义,仿佛:

var person = {firstName:..., lastName:...}; 

因此获得这些属性是通过构造函数的原型不受影响。

当一个新的对象被分配到构造函数的原型:

Person.prototype = {}; 

Object.prototype中(这是它的构造函数)继承了一个构造财产。因此,访问实例的构造函数首先在实例上查找,然后在其[[Prototype]](Person.prototype)上,然后在其[[Prototype]](Object.prototype)上查找并引用对象。您可以修复,通过这样做:

Person.prototype.constructor = Person; 

你可以找到关于MDN的更多信息:Inheritance and the prototype chain

2

构造一个对象不会将其constructor属性设置为构建它的函数。相反,函数的默认值prototype使用指向该函数的constructor属性进行初始化,该函数构造的对象从原型继承constructor属性。

当您替换函数的prototype时,替换不会自动获得分配给它的constructor属性的该函数。相反,新的prototype继承constructor原型,即Object.prototype。因此,该函数创建的对象现在将继承其原始模型Object.prototype中的Objectconstructor