【发布时间】:2022-10-18 12:14:44
【问题描述】:
以下代码示例使用众所周知的符号 Symbol.hasInstance 定义 static [Symbol.hasInstance](instance){...} 函数来自定义 instanceof 行为。
基本上,如果instance 对象定义了属性[Forgeable.isMagic],则此函数返回true。如果是这种情况,那么 instance 对象将被视为 Forgeable 类的实例。
// This class allows plain objects to be disguised as this class's instance,
// as long as the object has [Forgeable.isMagic] as its property.
class Forgeable {
static isMagic=Symbol();
static isMagic2=Symbol();
static [Symbol.hasInstance](instance) {
return Forgeable.isMagic in instance;
}
}
console.log('this object has static prop called isMagic', ({[Forgeable.isMagic]:'whatever'}) instanceof Forgeable);
console.log(({[Forgeable.isMagic2]:'whatever'}) instanceof Forgeable);
console.log(({}) instanceof Forgeable);
所以我确定我们的静态道具isMagic 是一个符号。
我的问题是为什么它需要成为代码才能工作的符号?如果我从isMagic 中删除符号分配,则代码将无法正常工作。我认为那是因为undefined in {undefined:'blah'} 返回true。
实际上,我尝试了static isMagic='blah',这似乎也有效。也许它只需要被分配一个值?
只是想确定一下。
我的想法是只需要为它分配除undefined 之外的任何值。但我只是想通过其他人的反馈来确定。我想知道,因为 Symbol() 在 MDN 的一个示例中被使用。
谢谢!
注意:此示例基于来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof 的示例
【问题讨论】:
标签: javascript symbols