原型继承:省略构造函数赋值时没有区别

Prototypal inheritance: no difference when omitting constructor assignment

参见这段原型继承代码:

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

Then what is worth of equalizing the function prototype constructor to function itself.

它有一些内在价值和一些实际用途。

首先,在派生的 class 原型上设置正确的构造函数可以保持 对称 。这意味着,属性 .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中得到了详细说明:


I am a newbie in JS.

我推荐你访问网站:http://www.javascripttutorial.net/

这是一个学习 JS 概念的好网站。