JavaScript/instanceof:修订间差异
来自康健生活
| 第51行: | 第51行: | ||
1n instanceof BigInt; | 1n instanceof BigInt; | ||
BigInt(1) instanceof BigInt; | BigInt(1) instanceof BigInt; | ||
new Map() instanceof Map; | |||
new Set() instanceof Set; | |||
var puz = new Promise((resolve,reject)=>{}); | |||
puz instanceof Promise; | |||
var xyz = new Proxy({},{}); | |||
xyz instanceof Proxy; | |||
</syntaxhighlight>|{{consoleout|<pre> | </syntaxhighlight>|{{consoleout|<pre> | ||
true | true | ||
| 第63行: | 第69行: | ||
false | false | ||
true | true | ||
true | |||
true | |||
true | |||
VM8385:2 Uncaught TypeError: Function has non-object prototype 'undefined' in instanceof check | |||
at Function.[Symbol.hasInstance] (<anonymous>) | |||
at <anonymous>:2:5 | |||
</pre>}}}} | </pre>}}}} | ||
== 原理 == | == 原理 == | ||
2020年6月26日 (五) 06:43的版本
引言
- 对于对象能返回构造对象的构造函数名。
- 能正确判断继承的对象。
- 对于原始类型字面量无法正确判断(Number,Boolean,String)。
- 对 new 构造的对象可以正确判断,可以正确判断原生类型(RegExp,Array,Function,Object)。
继承对象
原始类型
构造函数
原生类型
原理
模拟 instanceof
function simulateInstanceof (cloneObject, nativeObject) {
let CO_proto = cloneObject.__proto__;
let NO_prototype = nativeObject.prototype;
while(true) {
if(CO_proto == null) {
return false;
}
if(CO_proto == NO_prototype) {
return true;
}
CO_proto =CO_proto.__proto__;
}
}
let arr = new Array();
console.log(simulateInstanceof(arr,Array));
// ==> true
No categories