相关疑难解决方法(0)

Javascript中isPrototypeOf和instanceof有什么区别?

在我自己的一些旧代码中,我使用以下代码:

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)

javascript inheritance prototype instanceof

45
推荐指数
2
解决办法
1万
查看次数

Javascript:仍然被instanceof运算符搞糊涂了

文章如下定义的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)

javascript inheritance instanceof

5
推荐指数
1
解决办法
176
查看次数

标签 统计

inheritance ×2

instanceof ×2

javascript ×2

prototype ×1