gpt4 book ai didi

javascript instanceOf解释

转载 作者:行者123 更新时间:2023-11-30 13:06:34 26 4
gpt4 key购买 nike

我只是在玩 instanceof 运算符。我想知道我的理解是否正确

var C = function(){};
// in the above statement C has a "prototype" property which points to an object which has
// the constructor property which points to C constructor
var o1 = new C();
// in above statement o1.__proto__ is points to C.prototype. that means inheriting from C.prototype.
console.log(o1 instanceof C) // returns true
//instanceof will check o1.__proto__ is equals to C.prototype(recursively until it finds null object).
C.prototype = {};
console.log(o1 instanceof C) // false;
in the above case o1 was inherited from C.prototype which points to the different object not the present C.prototype object (empty object). so the instanceof condition check fails hence its false.

如果我的解释有误,请告诉我

最佳答案

是的,instanceof 检查对象原型(prototype)链中的构造函数,如果在链中的任何位置都找到传递的构造函数,则返回 true。所以如果你破坏了一个函数的原型(prototype),就像你用一个空对象覆盖它一样,那么 instanceof 将总是返回 false。

关于javascript instanceOf解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15485884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com