这似乎是许多人讨论过的事情。但不幸的是,我找不到我的问题的答案。这是一段关于 Javascript 继承的代码(来自一本书):
function Car() {
var self = this;
self.type = "Car"
self.go = function() {
console.log("Going...");
};
};
Toyota = function() { console.log("Original called"); };
Toyota.prototype = new Car();
Toyota.prototype.constructor = function() {
var self = this;
self.type = "Toyota";
self.go = function() {
console.log("A Toyota car is going...");
}
};
Toyota.prototype.isJapaneseCar = true;
function TestCar() {
console.log("Toyota.prototype.constructor: " + Toyota.prototype.constructor);
var t = new Toyota();
console.log("t.constructor: " + t.constructor);
console.log(t.type);
};
Firefox 控制台中的输出:
Toyota.prototype.constructor: function () {
var self = this;
self.type = "Toyota";
self.go = function () {
console.log("A Toyota car is going...");
};
}
Original called
t.constructor: function () {
var self = this;
self.type = "Toyota";
self.go = function () {
console.log("A Toyota car is going...");
};
}
Car
从输出中可以看出,新的 Toyota()调用:
var t = new Toyota();
没有像预期的那样调用Toyota.prototype.constructor函数,而是仍然调用最初定义的函数:
Toyota = function() { console.log("Original called"); };
高票数的帖子给出了相当详细的解释和示例:它说“ 3.它执行构造函数,只要提到这个,就会使用新对象。 ”提到的“构造函数”是指prototype.constructor吗?以下 3 行如何相关:
- Toyota = function() { console.log("原来叫"); }
- Toyota.prototype.constructor = function() { ...
- var t = new Toyota();
[编辑] 最让我困惑的是为什么当我调用new Toyota()时没有调用构造函数(Toyota.prototype.constructor) ?