2
見原型繼承的這個代碼:原型繼承:省略構造assingment時沒有區別
var Person = function() {
this.canTalk = true;
};
Person.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name);
}
};
var Employee = function(name, title) {
Person.call(this);
this.name = name;
this.title = title;
};
Employee.prototype = Object.create(Person.prototype);
// Note: there's no difference, when I comment out the following line
Employee.prototype.constructor = Employee;
Employee.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name + ', the ' + this.title);
}
};
var bob = new Employee('Bob', 'Builder');
bob.greet();
我得到了相同的結果(控制檯輸出),即使我註釋掉線
Employee.prototype.constructor = Employee;
那麼什麼是值得平衡的功能原型構造函數本身。我是JS的新手。此外,如果它影響長期。 如何?我不想要任何解決方法。
'(new function Foo(){})。constructor; // function Foo(){}' –
[爲什麼需要設置原型構造函數?](http://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-原型構造函數) –
當你重載默認原型時,你會丟失關於構造函數等的數據; 'Bar(){};''Bar.prototype = Object.create({});'現在有'(new Bar())。constructor; //函數Object(){[native code]}',即不是'Bar' –