我的博客 上),碰到一些知识点是自己已经忘记(用得少的知识点),于是也重新复习了一遍。
这篇文章要复习的 instanceof
是我在整理过程中遇到的,那就整理下来吧,不然容易忘记。
要是哪里写得不妥,欢迎各位大佬指点。
1.定义
instanceof
运算符用于测试构造函数的prototype
属性是否出现在对象的原型链中的任何位置。 —— MDN
简单理解为:instanceof
可以检测一个实例是否属于某种类型。
比如:
function F (){
}
let a = new F ();
a instanceof F;
a instanceof Object;
还可以在继承关系中用来判断一个实例是否属于它的父类型。
比如:
function F (){};
function G (){};
function Q (){};
G.prototype = new F();
let a = new G();
a instanceof F;
a instanceof G;
a instanceof Q;
2.使用方法
语法为: object instanceof constructor
。
-
object
: 需要测试的函数
-
constructor
: 构造函数
即:用instanceof
运算符来检测constructor.prototype
是否存在参数object
的原型链。
function F (){};
function G (){};
let a = new F ();
a instanceof F;
a instanceof Q;
a instanceof Object;
F.prototype instanceof Object;
注意:
-
a instanceof F
返回 true
以后,不一定永远都都返回为true
,F.prototype
属性的值有可能会改变。
- 原表达式
a
的值也会改变,比如 a.__proto__ = {}
之后,a instanceof F
就会返回false
了。
检测对象是不是特定构造函数的实例:
if (!(obj instanceof F)) {
}
if (!obj instanceof F);
3.实现instanceof
function _instanceof(obj, fun) {
let f = fun.prototype;
obj = obj.__proto__;
while (true) {
if (obj === null)
return false;
if (f === obj)
return true;
obj = obj.__proto__;
}
}
4.instanceof 与 typeof 对比
相同:
instanceof
和typeof
都能用来判断一个变量的类型。
区别:
instanceof
只能用来判断对象、函数和数组,不能用来判断字符串和数字等:
let a = {};
let b = function () {};
let c = [];
let d = 'hi';
let e = 123;
a instanceof Object;
b instanceof Object;
c instanceof Array;
d instanceof String;
e instanceof Number;
typeof
:用于判断一个表达式的原始值,返回一个字符串。
typeof 42;
typeof 'blubber';
typeof true;
typeof aa;
一般返回结果有:
- number
- boolean
- string
- function(函数)
- object(NULL,数组,对象)
- undefined。
判断变量是否存在:
不能使用:
if(a){
}
原因是如果变量未定义,就会报未定义的错,而应该使用:
if(typeof a != 'undefined'){
}
5.参考资料
-
MDN instanceof
-
IBM instanceof
-
js中typeof和instanceof用法区别