重新实现的构造函数 [Symbol.hasInstance] 但它仍然不会被调用 [英] Reimplemented Constructor[Symbol.hasInstance] but it still won't be called

查看:73
本文介绍了重新实现的构造函数 [Symbol.hasInstance] 但它仍然不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在编写一些示例代码,为 Constructor[Symbol.hasInstance] 实现另一个函数,但我注意到我的新实现不会被调用.

So, I was writing some example code implementing another function for Constructor[Symbol.hasInstance] and I noticed my new implementation just won't get called.

下面的脚本是我期望发生的:

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

我尝试向我的 Pirate[Symbol.hasInstance] 实现添加一个 console.log 调用,但它不会将任何内容记录到控制台.

I tried to add a console.log call to to my Pirate[Symbol.hasInstance] implementation, but it won't log anything to the console.

有人知道发生了什么吗?为什么我的实现没有被调用?

Does anyone have any idea of what is happening? Why is my implementation not getting called?

我在 Node 6.9.1 上运行它.

I'm running this on Node 6.9.1.

推荐答案

你可以找到答案

Object.getOwnPropertyDescriptor( Function.prototype, Symbol.hasInstance).writable

它返回 false:您不能使用赋值 = 运算符写入函数的 Symbol.hasInstance 属性.该属性永远不会被设置,因此它永远不会被调用.(默默地失败对我来说是一种无益的行为,但你去了.如果你处于严格模式,一个 TypeError 会抛出一个有用的消息,这是你应该一直使用它的众多原因之一.) 您只能在具有 Object.defineProperty 的函数上定义 Symbol.hasInstance 属性.

It returns false: you cannot write to the Symbol.hasInstance property of a function with the assignment = operator. The property never gets set and so it never gets called. (Failing silently feels like unhelpful behaviour to me, but there you go. A TypeError is thrown with a helpful message if you are in strict mode, one of the many reasons you should use it all the time.) You can only define the Symbol.hasInstance property on a function with Object.defineProperty.

Object.defineProperty(Pirate, Symbol.hasInstance, {
    value: function(anObj) {
        console.log('Is he a pirate?');
        return anObj.isPirate;
    }
});

现在jackSparrow instanceof Pirate首先记录问题,然后返回true.

Now jackSparrow instanceof Pirate first logs the question, then returns true.

这篇关于重新实现的构造函数 [Symbol.hasInstance] 但它仍然不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆