公告

👇公众号👇---👇 微信 👇

欢迎大家私信&加群交流

Skip to content

instanceof能正确判断对象的原因是什么

粥里有勺糖 2020-04-14面试javascript 119 个字 1 分钟
  • 通过原型链进行判断的
  • 每个对象都有一个原型,instanceof会沿着原型链进行判断,直到最顶层原型为止
  • 可以通过Symbol.hasInstance重定义instanceof的行为,所以instanceof的结果不一定绝对正确
js
function myString() {

}
Object.defineProperty(myString, Symbol.hasInstance, {
    value: function (str) {
        return typeof str === 'string'
    },
    enumerable: false,
    configurable: true
})
console.log('ss' instanceof myString); // true
评论