JavaScript - Symbol.hasInstance 属性
在 JavaScript 中,一个名为 Symbol.hasInstance 属性的独特符号允许对象指定在使用 intnanceof 运算符时的行为。当将 Symbol.hasInstance 指定为对象的方法时,它会控制使用 intnanceof 运算符生成的实例在针对该对象进行测试时的行为。
使用此符号,用户定义的对象可以自定义 intnanceof 运算符的行为,从而更自由地确定对象是否是特定构造函数的实例。
语法
以下是 JavaScript Symbol.hasInstance 属性的语法 -
[Symbol.hasInstance](Object)
参数
此方法仅接受一个参数。下文同样描述 -
object - 对象是构造函数之一。
返回值
如果值在对象的链中,则返回 true,否则返回 false。
示例
示例 1
让我们看下面的示例,我们将为自定义类自定义实例。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
static[Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
const a = [11, 2, 33];
document.write(a instanceof x);
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示文本。
示例 2
考虑另一种场景,我们将为自定义对象自定义实例。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function examp() {}
const x = new examp();
examp[Symbol.hasInstance] = function(instance) {
return instance.constructor && instance.constructor.name === "TP";
};
document.write(x instanceof examp);
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将使用带有 Symbol.hasInstance 属性的自定义构造函数。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function examp() {}
examp[Symbol.hasInstance] = function(instance) {
return instance instanceof examp && instance.isValid();
};
const x = new examp();
document.write(x instanceof examp);
</script>
</body>
</html>
当我们执行脚本时,它将在网页上显示一段文本。
示例 4
以下示例将使用 Symbol.hasInstance 和继承。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
static[Symbol.hasInstance](instance) {
return 'dance' in instance && typeof instance.dance === 'function';
}
}
class y {
dance() {
document.write("cat is dancing");
}
}
let cat = new y();
document.write(cat instanceof x);
</script>
</body>
</html>
执行上述脚本后,将弹出输出窗口,显示网页上的文本。

