【发布时间】:2015-08-04 10:22:07
【问题描述】:
article 定义 instanceof 如下:
instanceof 操作符测试一个对象是否在其原型中 链接构造函数的原型属性。
这是一个公平的解释,生活很美好,直到我从 Eloquent Javascript 一书中看到这段代码:
function TextCell(text) {
this.text = text.split("\n");
}
TextCell.prototype.minWidth = function() {
return this.text.reduce(function(width, line) {
return Math.max(width, line.length);
}, 0);
}
TextCell.prototype.minHeight = function() {
return this.text.length;
}
TextCell.prototype.draw = function(width, height) {
var result = [];
for (var i = 0; i < height; i++) {
var line = this.text[i] || "";
result.push(line + repeat(" ", width - line.length));
}
return result;
}
function RTextCell(text) {
TextCell.call(this, text);
}
RTextCell.prototype = Object.create(TextCell.prototype);
RTextCell.prototype.draw = function(width, height) {
var result = [];
for (var i = 0; i < height; i++) {
var line = this.text[i] || "";
result.push(repeat(" ", width - line.length) + line);
}
return result;
};
让我们创建一个 RTextCell 的实例并执行下面的 c
var rt = new RTextCell("ABC");
console.log(rt instanceof RTextCell); // true
console.log(rt instanceof TextCell); // true
我理解为什么第二个 console.log 的输出是“真”——因为构造函数 TextCell 是原型链的一部分。
但是第一个 console.log 让我感到困惑。
如果看代码(倒数第 10 行),RTextCell 的原型被更新为一个新的 Object,其原型设置为 TextCell.prototype。
RTextCell.prototype = Object.create(TextCell.prototype);.
看下面的快照,对象“rt”的原型链中没有提到构造函数“RTextCell”。那么,按照我在文章开头提到的定义,输出不应该是假的吗?为什么会返回真值?
我也阅读了this,但没有帮助我理解这个具体问题。
rt、RTextCell、TextCell 的快照按顺序见下文。
【问题讨论】:
-
这是一个结构很好的问题。您展示了您之前的所有调查,希望您得到很好的答案。
-
哦!我应该补充。我在 chrome 43.0.2357.65 和 firefox 33.1.1 上的上述快照中检查了这个原型链树。
标签: javascript inheritance instanceof