在 JavaScript 中,一个名为 Symbol.hasInstance 属性的唯一元件使对象能够指定它们在使用 instanceof 运算符时的行为方式。Symbol.hasInstance 时,当指定为对象上的方法时,它控制在针对对象进行测试时使用 instanceof 生成的实例的行为。
使用此符号,用户定义的对象可以自定义 instanceof 运算符的行为,从而在决定对象是否为特定构造函数的实例时具有更大的自由度。
语法
以下是 JavaScript Symbol.hasInstance 属性的语法 -
[Symbol.hasInstance](Object)
参数
此方法只接受一个参数。下面描述相同 -
- object − 对象是构造函数之一。
返回值
如果值在对象的链中,则返回 true,否则返回 false。
示例 1
让我们看看下面的示例,我们将在其中为自定义类自定义 instanceof。
<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
考虑另一个场景,我们将为自定义对象自定义 instanceof。
<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 和 Inheritance。
<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>
在执行上述脚本时,将弹出输出窗口,在网页上显示文本。