typeof是一个运算符,用于检测数据的类型,比如基本数据类型null、undefined、string、number、boolean,以及引用数据类型object、function,但是对于正则表达式、日期、数组这些引用数据类型,它会全部识别为object;
语法:typeof operand typeof(operand) 参数:operand(
一个表示对象或原始值的表达式,其类型将被返回)
(typeof 42);
// expected output: "number"
(typeof 'blubber');
// expected output: "string"
(typeoftrue);
// expected output: "boolean"
(typeof undeclaredVariable);
// expected output: "undefined"
下表总结了 typeof
可能的返回值。
instanceof同样也是一个运算符,它就能很好识别数据具体是哪一种引用类型。它与isPrototypeOf的区别就是它是用来检测构造函数的原型是否存在于指定对象的原型链当中;
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
(auto instanceof Car);
// expected output: true
(auto instanceof Object);
// expected output: true
语法 :object instanceof constructor 【
参数 object (
某个实例对象);
constructor(某个构造函数)】
isPrototypeOf是用来检测调用此方法的对象是否存在于指定对象的原型链中,所以本质上就是检测目标不同。
function object1() {}
function object2() {}
object1.prototype = Object.create();
const object3 = new object1();
((object3));
// expected output: true
(.isPrototypeOf(object3));
// expected output: true
isPrototypeOf()
与instanceof
运算符不同。在表达式“ object instanceof AFunction
”中,对object
原型链进行检查,而不是对
AFunction
自身进行检查。
句法:prototypeObj.isPrototypeOf(object) [
参量:object(将搜索其原型链的对象).
返回值:Boolean
指示是否调用对象在于指定的对象的原型链.抛出错误:TypeError(
TypeError
如果prototypeObj
未定义或为null,则抛出A)]