Javascript 重新实现了构造函数[Symbol.hasInstance],但它仍然赢了';别叫了
所以,我在为Javascript 重新实现了构造函数[Symbol.hasInstance],但它仍然赢了';别叫了,javascript,metaprogramming,Javascript,Metaprogramming,所以,我在为构造函数[Symbol.hasInstance]编写一些实现另一个函数的示例代码,我注意到我的新实现不会被调用 下面的脚本是我所期望的: function Pirate(name) { this.name = name; } const jackSparrow = { isPirate: true }; // Notice how `jackSparrow` is not yet considered an instance of the `Pirate` obj
构造函数[Symbol.hasInstance]
编写一些实现另一个函数的示例代码,我注意到我的新实现不会被调用
下面的脚本是我所期望的:
function Pirate(name) {
this.name = name;
}
const jackSparrow = {
isPirate: true
};
// Notice how `jackSparrow` is not yet considered an instance of the `Pirate` object
console.log(jackSparrow instanceof Pirate); // false
// Now let's assign another function for `Pirate[Symbol.hasInstance]`
Pirate[Symbol.hasInstance] = function (anObj) {
return anObj.isPirate;
};
// This will cause Pirate[Symbol.hasInstance] to be called with `jackSparrow`
console.log(jackSparrow instanceof Pirate); // true
我试图将console.log
调用添加到我的海盗[Symbol.hasInstance]实现中,但它不会将任何内容记录到控制台中
有人知道发生了什么吗?为什么我的实现没有被调用
我正在节点6.9.1上运行此操作。如果您这样做,您可以找到答案
Object.getOwnPropertyDescriptor( Function.prototype, Symbol.hasInstance).writable
它返回false
:不能写入符号。使用赋值=
运算符的函数的hasInstance
属性。属性从未被设置,因此它从未被调用。(无声地失败对我来说是没有帮助的行为,但你就这样做了。如果你处于严格模式,会抛出一个TypeError
,并显示一条有用的消息,这是你应该一直使用它的原因之一。)你只能在带有Object.defineProperty
的函数上定义符号.hasInstance
属性
Object.defineProperty(Pirate, Symbol.hasInstance, {
value: function(anObj) {
console.log('Is he a pirate?');
return anObj.isPirate;
}
});
现在,jackSparrow instanceof Pirate
首先记录问题,然后返回true
解释原因。如果对象已将属性继承为不可写,则指定不会定义该属性
如果您不想使用显式属性定义,请考虑使用类语法:
class海盗{
建造师(姓名){
this.name=名称;
}
静态[Symbol.hasInstance](anObj){
返回anObj.isPirate;
}
}
常数jackSparrow={
伊斯皮拉特:对
};
console.log(jackSparrow海盗实例);//true
…或使用带有静态[Symbol.hasInstance](obj){…}
方法的类定义这绝对是ES6ish的好答案!我不是ES6课程的超级粉丝,但谢谢你!