How does instanceof work in JavaScript?

前端 未结 2 1264
我寻月下人不归
我寻月下人不归 2020-12-01 23:58

In the following code sample both checks of obj2 and obj3 at the end with instanceof return true even if the ways there were constructed are different and the resul

2条回答
  •  既然无缘
    2020-12-02 00:38

    Most simply: obj instanceof constructor yields true when obj has constructor's prototype in it's constructor/prototype chain. In other words, your asking your engine whether obj can be treated like an instance of constructor / whether obj behaves like a constructor object.

    There is a small handful of syntaxes that allow you to put constructor's prototype in obj's prototype chain. Any and all of them will cause obj instanceof constructor to be true. In your examples, both obj2 and obj3 have Obj1 in their prototype chain.

    So, when you ask your javascript engine whether either obj2 or obj3 behave like an instance of Obj1, JavaScript assumes true -- the only case wherein they wouldn't is if you've overridden Obj1's behavior down the line.

提交回复
热议问题