What does this instanceof error message mean?

心已入冬 提交于 2019-12-12 07:24:59

问题


I was playing around with instanceof in Chrome but I got an error message. I think I know why (you have to supply a function after the instanceof keyword that is the constructor the object was created with), but the error message seems to be stating something else:

[1,2,3] instanceof Array
// true

[1,2,3] instanceof []
// TypeError: Expecting a function in instanceof check, but got 1,2,3

Does this mean that I should replace [1,2,3] with a function? I would think that [1,2,3] is correct and that [] is the problem and should be replaced with a function, but it looks like the error message is saying the opposite.

Could someone please explain how I'm interpreting the error message incorrectly?


回答1:


Objects are instances of a constructor function, so the test is to see if the left hand is an instance of the right, so the right must be a function (and it must be the constructor that constructed the object to return true).

[1,2,3] instanceof [].constructor;  // true

So to answer the question more directly, your initial understanding is correct, and the error message seems misleading (to me anyway).

From the spec: http://ecma262-5.com/ELS5_HTML.htm#Section_11.8.6

1.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.

and http://ecma262-5.com/ELS5_HTML.htm#Section_15.3.5

15.3.5 Properties of Function Instances

In addition to the required internal properties, every function instance has a [[Call]] internal property and in most cases use a different version of the [[Get]] internal property. Depending on how they are created (see 8.6.2 ,13.2, 15, and 15.3.4.5), function instances may have a [[HasInstance]] internal property, a [[Scope]] internal property, a [[Construct]] internal property, a [[FormalParameters]] internal property, a [[Code]] internal property, a [[TargetFunction]] internal property, a [[BoundThis]] internal property, and a [[BoundArgs]] internal property.

So it requires a TypeError if the right hand does not have an internal [[HasInstance]] property, but doesn't specify the wording.

Firefox 4 gives me a much more sensible error message:

[1,2,3] instanceof [];

// TypeError: invalid 'instanceof' operand []


来源:https://stackoverflow.com/questions/6021245/what-does-this-instanceof-error-message-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!