在我自己的一些旧代码中,我使用以下代码:
Object.prototype.instanceOf = function( iface )
{
return iface.prototype.isPrototypeOf( this );
};
Run Code Online (Sandbox Code Playgroud)
然后我做(例如)
[].instanceOf( Array )
Run Code Online (Sandbox Code Playgroud)
这有效,但似乎以下情况也是如此:
[] instanceof Array
Run Code Online (Sandbox Code Playgroud)
现在,这肯定只是一个非常简单的例子.因此,我的问题是:
是否a instanceof b 总是一样的b.prototype.isPrototypeOf(a)?
该文章如下定义的instanceof:
instanceof运算符测试对象在其原型链中是否具有构造函数的prototype属性.
这是一个公平的解释,生活很好,直到我从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 …Run Code Online (Sandbox Code Playgroud)