javascript - JavaScript中instanceof是如何实现的

标签 javascript

让我们考虑以下代码片段:

function A() {}
var obj = new A();
function B() {};
obj.constructor = B;
console.info("1: ", obj.constructor); //Function B
console.info("2: ", obj instanceof A); //true
console.info("3: ", obj instanceof B); //false

我的猜测是,要确定对象是否是某个函数类的实例,JS 引擎必须检查该对象是否具有相同的构造函数属性。但它似乎并没有发生,因为即使覆盖对象的构造函数属性也不会改变它的 instanceof 输出。

最佳答案

ECMAScript 262 规范会告诉您这一点。直接引用其The `instanceof operator部分:

11.8.6 The instanceof operator

The production RelationalExpression : RelationalExpression instanceof ShiftExpression is evaluated as follows:

  1. Let lref be the result of evaluating RelationalExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating ShiftExpression.
  4. Let rval be GetValue(rref).
  5. If Type(rval) is not Object, throw a TypeError exception.
  6. If rval does not have a [[HasInstance]] internal method, throw a TypeError exception.
  7. Return the result of calling the [[HasInstance]] internal method of rval with argument lval.

至于[[HasInstance]]是什么,规范也在其Object Internal Properties and Methods中进行了定义。部分为:

[[HasInstance]]

Returns a Boolean value indicating whether the argument is likely an Object that was constructed by this object. Of the standard built-in ECMAScript objects, only Function objects implement [[HasInstance]]

进一步阅读:http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.5.3

关于javascript - JavaScript中instanceof是如何实现的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29540807/

相关文章:

javascript - 创建一个数组的数组

javascript - 在 repl 中导入 es6 模块

javascript - Bootstrap Modal 缩小动画

javascript - 如何创建多个高度为 100% 的 div?

javascript - 嵌入然后替换为 angularjs

javascript - 有没有办法用 async/await 而不是 Promise 返回一个值?作为一个同步函数做

javascript - 如何在 fullcalendar.js 上拖放两个事件

javascript - 在 angularJS 中使用自定义 Canvas 指令不会显示任何内容

javascript - 如何使用倍数解析实例

javascript - gulpfile.js - 任务不在 gulp 文件中错误