JavaScript 元编程中的知名符号与模板标签
1. Symbol.hasInstance
在 JavaScript 中, instanceof 运算符以往要求右侧必须是构造函数,表达式 o instanceof f 会在 o 的原型链中查找 f.prototype 的值。但在 ES6 及以后, Symbol.hasInstance 提供了另一种方式。
如果 instanceof 的右侧对象有 [Symbol.hasInstance] 方法,该方法会以左侧的值作为参数被调用,其返回值转换为布尔值后就是 instanceof 运算符的值。若右侧值没有 [Symbol.hasInstance] 方法但为函数, instanceof 运算符则按常规方式工作。
示例代码如下:
// Define an object as a "type" we can use with instanceof
let uint8 = {
[Symbol.hasInstance](x) {
return Number.isInteger(x) && x >= 0 && x <= 255;
}
};
console.log(128 instance
超级会员免费看
订阅专栏 解锁全文
1399

被折叠的 条评论
为什么被折叠?



