2017-02-05 65 views
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的新手。此外,如果它影响长期。 如何?我不想要任何解决方法。

+0

'(new function Foo(){})。constructor; // function Foo(){}' –

+0

[为什么需要设置原型构造函数?](http://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-原型构造函数) –

+1

当你重载默认原型时,你会丢失关于构造函数等的数据; 'Bar(){};''Bar.prototype = Object.create({});'现在有'(new Bar())。constructor; //函数Object(){[native code]}',即不是'Bar' –

回答

0

那么什么是值得均衡函数原型构造函数本身。

它有一些内在的价值和一些实际用途。首先,在派生类的原型上设置正确的构造函数,使对象对称。这意味着,财产.constructor服务的目的是直观地建议哪个功能创建此对象

var Person = function() {}; 
var Employee = function() {}; 

Employee.prototype = Object.create(Person.prototype); 
Employee.prototype.constructor = Employee; 

var bob = new Employee(); 

console.log(bob.constructor); 
console.log(bob.__proto__.constructor); 
console.log(bob.__proto__.__proto__.constructor); 
console.log(bob.__proto__.__proto__.__proto__.constructor); 

// [Function: Employee] 
// [Function: Employee] 
// [Function: Person] 
// [Function: Object] 


var Person = function() {}; 
var Employee = function() {}; 

Employee.prototype = Object.create(Person.prototype); 
// Employee.prototype.constructor = Employee; 

var bob = new Employee(); 

console.log(bob.constructor); 
console.log(bob.__proto__.constructor); 
console.log(bob.__proto__.__proto__.constructor); 
console.log(bob.__proto__.__proto__.__proto__.constructor); 

// [Function: Person] 
// [Function: Person] 
// [Function: Person] 
// [Function: Object] 

其次,如果你需要使用构造函数,你可以从.constructor参考使用它,而不是使用功能名称。这一点在本asnwer详细阐述:https://stackoverflow.com/a/8454111/1343488


我在JS一个新手。

我建议您访问以下网址:http://www.javascripttutorial.net/

这是一个伟大的网站上晚自习JS概念。