Symbol.hasInstance
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.
Thuộc tính dữ liệu tĩnh Symbol.hasInstance đại diện cho well-known symbol Symbol.hasInstance. Toán tử instanceof tra cứu symbol này trên toán hạng bên phải của nó cho phương thức dùng để xác định xem đối tượng constructor có nhận dạng một đối tượng là instance của nó không.
Try it
class Array1 {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof Array1);
// Expected output: true
Giá trị
Well-known symbol Symbol.hasInstance.
Property attributes of Symbol.hasInstance | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Mô tả
Toán tử instanceof sử dụng thuật toán sau để tính toán giá trị trả về của object instanceof constructor:
- Nếu
constructorcó phương thức[Symbol.hasInstance](), thì gọi nó vớiobjectlà đối số đầu tiên và trả về kết quả, ép kiểu thành boolean. NémTypeErrornếuconstructorkhông phải là đối tượng, hoặc nếuconstructor[Symbol.hasInstance]không phải là một trong sốnull,undefined, hoặc một hàm. - Nếu không, nếu
constructorkhông có phương thức[Symbol.hasInstance]()(constructor[Symbol.hasInstance]lànullhoặcundefined), thì xác định kết quả bằng cùng thuật toán nhưFunction.prototype[Symbol.hasInstance](). NémTypeErrornếuconstructorkhông phải là hàm.
Vì tất cả các hàm kế thừa từ Function.prototype theo mặc định, hầu hết thời gian, phương thức Function.prototype[Symbol.hasInstance]() chỉ định hành vi của instanceof khi vế phải là một hàm.
Ví dụ
>Hành vi instanceof tùy chỉnh
Bạn có thể triển khai hành vi instanceof tùy chỉnh của mình như sau:
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true
function MyArray() {}
Object.defineProperty(MyArray, Symbol.hasInstance, {
value(instance) {
return Array.isArray(instance);
},
});
console.log([] instanceof MyArray); // true
Kiểm tra instance của một đối tượng
Cũng giống như cách bạn kiểm tra xem một đối tượng có phải là instance của một class bằng từ khóa instanceof, bạn cũng có thể dùng Symbol.hasInstance cho các kiểm tra như vậy.
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
Đặc tả
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-symbol.hasinstance> |