3

看看下面的例子,其中来自PersonStudent继承:在继承Javascript中的对象时需要“Subclass.prototype.constructor = Subclass”吗?

function Person(name) { 
    this.name = name; 
} 
Person.prototype.say = function() { 
    console.log("I'm " + this.name); 
}; 

function Student(name, id) { 
    Person.call(this, name); 
    this.id = id; 
} 
Student.prototype = new Person(); 
// Student.prototype.constructor = Student; // Is this line really needed? 
Student.prototype.say = function() { 
    console.log(this.name + "'s id is " + this.id); 
}; 

console.log(Student.prototype.constructor); // => Person(name) 

var s = new Student("Misha", 32); 
s.say();          // => Misha's id is 32 

正如你所看到的,实例化一个对象Student并调用其方法工作得很好,但Student.prototype.constructor回报Person(name),这似乎是我错了。

如果我添加:

Student.prototype.constructor = Student; 

然后Student.prototype.constructor回报Student(name, id),符合市场预期。

我应该总加Student.prototype.constructor = Student吗?

你可以举个例子吗?

+0

的可能重复[什么是JavaScript构造属性的意义是什么?(http://stackoverflow.com/questions/4012998/what-it-the-significance-of-the-javascript-constructor-属性) – Domenic

回答