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 2017å¹´4æ.
Symbol.hasInstance ã¯éçãã¼ã¿ããããã£ã§ãã¦ã§ã«ãã¦ã³ã·ã³ãã«ã® Symbol.hasInstance ã表ãã¾ããinstanceof æ¼ç®åã¯å³è¾ºãªãã©ã³ãã«å¯¾ãã¦ãã³ã³ã¹ãã©ã¯ã¿ã¼ãªãã¸ã§ã¯ãããªãã¸ã§ã¯ãããã®ã¤ã³ã¹ã¿ã³ã¹ã¨ãã¦èªèãããã©ããã夿ããéã«ä½¿ç¨ãããã¡ã½ãããããã®ã·ã³ãã«ã§æ¢ãã¾ãã
試ãã¦ã¿ã¾ããã
class Array1 {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof Array1);
// äºæ³ãããçµæ: true
å¤
ã¦ã§ã«ãã¦ã³ã·ã³ãã« Symbol.hasInstance ã§ãã
Symbol.hasInstance ã®ããããã£å±æ§ | |
|---|---|
| æ¸è¾¼å¯è½ | ä¸å¯ |
| åæå¯è½ | ä¸å¯ |
| è¨å®å¯è½ | ä¸å¯ |
解説
instanceof æ¼ç®åã¯ãobject instanceof constructor ã®è¿å¤ãè¨ç®ããããã«ä»¥ä¸ã®ã¢ã«ã´ãªãºã ã使ç¨ãã¾ãã
constructorã«[Symbol.hasInstance]()ã¡ã½ããããã£ãå ´åãobjectãæåã®ãªãã¸ã§ã¯ãã¨ãã¦å¼ã³åºããçµæãè«çå¤ã«å¤æãã¦è¿ãã¾ããconstructorããªãã¸ã§ã¯ãã§ãªãå ´åãã¾ãã¯constructor[Symbol.hasInstance]ãnullãundefinedã颿°ã®ãããã§ãã§ãªãå ´åãTypeErrorãçºçãã¾ãã- ãã以å¤ã®å ´åã
constructorã«[Symbol.hasInstance]()ã¡ã½ããããªãå ´åï¼constructor[Symbol.hasInstance]ãnullã¾ãã¯undefinedï¼ãFunction.prototype[Symbol.hasInstance]()ã¨åãã¢ã«ã´ãªãºã ã使ç¨ãã¦çµæã決å®ãã¾ããconstructorã颿°ã§ãªãå ´åãTypeErrorãçºçãã¾ãã
Because all functions inherit from Function.prototype by default, most of the time, the Function.prototype[Symbol.hasInstance]() method specifies the behavior of instanceof when the right-hand side is a function.
ä¾
>ç¬èªã®ã¤ã³ã¹ã¿ã³ã¹ã§ã®åä½
ãã¨ãã°ã次ã®ããã«ã㦠instanceof ã®ç¬èªã®åä½ãå®è£
ãããã¨ãã§ãã¾ãã
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
ãªãã¸ã§ã¯ãã®ã¤ã³ã¹ã¿ã³ã¹ã確èªãã
instanceof ãã¼ã¯ã¼ãã使ã£ã¦ãªãã¸ã§ã¯ããã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ã§ãããã©ããã確èªããã®ã¨åãæ¹æ³ã§ãSymbol.hasInstance ã使ã£ã¦ç¢ºèªãããã¨ãã§ãã¾ãã
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
仿§æ¸
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-symbol.hasinstance> |