JavaScript/instanceof:修订间差异
来自康健生活
无编辑摘要 |
|||
| 第1行: | 第1行: | ||
== 引言 == | |||
== 继承对象 == | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
class People{}; | |||
class Student extends People{}; | |||
new Student() instanceof Student; | |||
new Student() instanceof People; | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
true | |||
true | |||
</pre>}}}} | |||
== 原始类型 == | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
1 instanceof Number; | |||
true instanceof Boolean; | |||
"str" instanceof String; | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
false | |||
false | |||
false | |||
</pre>}}}} | |||
== 构造函数 == | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
new Number(1) instanceof Number; | |||
new Boolean(true) instanceof Boolean; | |||
new String('str') instanceof String; | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
true | |||
true | |||
true | |||
</pre>}}}} | |||
== 原生类型 == | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
[1,2,3] instanceof Array; | |||
/abc/ instanceof RegExp; | |||
({}) instanceof Object; | |||
function foo(){} | |||
foo instanceof Function; | |||
[1,2,3] instanceof Object; | |||
/abc/ instanceof Object; | |||
function bar(){} | |||
bar instanceof Object; | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
true | |||
true | |||
true | |||
true | |||
true | |||
true | |||
true | |||
</pre>}}}} | |||
== 模拟 instanceof == | == 模拟 instanceof == | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
2020年6月26日 (五) 06:25的版本
引言
继承对象
原始类型
构造函数
原生类型
模拟 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