JavaScript/instanceof:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第77行: 第77行:
</pre>}}}}
</pre>}}}}
== 复杂用法 ==
== 复杂用法 ==
{{leftrightflex|<syntaxhighlight lang="javascript">
function Foo(){}
Object instanceof Object;
Function instanceof Function;
Number instanceof Number;
String instanceof String;
Function instanceof Object;
Foo instanceof Function;
Foo instanceof Foo;
</syntaxhighlight>|{{consoleout|<pre>
true
true
false
false
true
true
false
</pre>}}}}
== 继承 ==
{{leftrightflex|<syntaxhighlight lang="javascript">
function Aoo(){}
function Foo(){}
Foo.prototype = new Aoo();
var foo = new Foo();
console.log(foo instanceof Foo);
console.log(foo instanceof Aoo);
</syntaxhighlight>|{{consoleout|<pre>true
true
</pre>}}}}


== 原理 ==
== 原理 ==

2020年6月26日 (五) 06:53的版本

引言

  • 对于对象能返回构造对象的构造函数名。
  • 能正确判断继承的对象。
  • 对于原始类型字面量无法正确判断(Number,Boolean,String)。
  • 对 new 构造的对象可以正确判断,可以正确判断原生类型(RegExp,Array,Function,Object)。

继承对象

模板:Leftrightflex

原始类型

模板:Leftrightflex

构造函数

模板:Leftrightflex

原生类型

模板:Leftrightflex

复杂用法

模板:Leftrightflex

继承

模板:Leftrightflex

原理

模拟 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