让我们考虑以下代码片段:
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:
- Let lref be the result of evaluating RelationalExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating ShiftExpression.
- Let rval be GetValue(rref).
- If Type(rval) is not Object, throw a TypeError exception.
- If rval does not have a [[HasInstance]] internal method, throw a TypeError exception.
- 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/