这是一个很好的解释,但当我看到《JavaScript高级程序设计》中的代码时,就有些不理解了:instanceof 运算符用于检测构造函数的原型属性是否出现在某个实例对象的原型链上。
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的实例,并执行以下操作
var rt = new RTextCell("ABC");
console.log(rt instanceof RTextCell); // true
console.log(rt instanceof TextCell); // true
我知道为什么第二个console.log的输出是"true"——因为构造函数TextCell是原型链的一部分。
然而,第一个console.log让我感到困惑。
如果你看看代码(从底部的第10行开始),RTextCell的原型被更新为一个新对象,其原型被设置为TextCell.prototype。
RTextCell.prototype = Object.create(TextCell.prototype);
。
查看下面的快照,对象"rt"的原型链中没有提到构造函数"RTextCell"。因此,根据我在文章开头提到的定义,输出不应该是false吗?为什么会返回true?
我还阅读了这个,但对于理解这个具体问题没有帮助。
请参见以下快照,依次显示了"rt"、"RTextCell"、"TextCell"的快照。