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' –