基本数据类型的检测
typeof
tpeof [val]:用来检测数据类型的运算符。
基于typeof检测出来的结果:
- 首先是一个字符串
- 字符串中是对应的类型
局限性:
- typeof null =>“object” 但是null并不是对象
- 基于typeof 无法细分出当前值是普通对象还是数组对象等,只要是对象类型,返回结果都是"object"
- typeof可以检测基本类型,但引用类型均返回object(function 返回 Function)
instanceof
console.log('1' instanceof String); //false
console.log(1 instanceof Number); //false
console.log(true instanceof Boolean); //false
console.log(function(){} instanceof Function); //true
console.log([] instanceof Array); //true
instanceof 可以用于引用类型的检测,但对于基本类型是不生效的,另外:不能用于检测null 和 undefined。
constructor
console.log(("1").constructor === String); //true
console.log((1).constructor === Number); //true
console.log((true).constructor === Boolean); //true
console.log(([]).constructor === Array); //true
console.log((function() {}).constructor === Function); //true
console.log(({}).constructor === Object); //true
constructor方法不能用于检测null
和undefined
Object.prototype.toString.call()
var test = Object.prototype.toString;
console.log(test.call("str"));
console.log(test.call(1));
console.log(test.call(true));
console.log(test.call(null));
console.log(test.call(undefined));
console.log(test.call([]));
console.log(test.call(function() {}));
console.log(test.call({}));
结果:
[object String]
[object Number]
[object Boolean]
[object Null]
[object Undefined]
[object Array]
[object Function]
[object Object]
这个方法可以用来检测任意类型的数据。
原型对象的检测
原型对象关系的检测
isPrototypeOf :
确定对象之间是否存在某种关系。
getPropertyOf
Object.getPropertyOf()返回的是这个对象的原型。
//前提:Person是构造函数,person2是实例对象
log(Person.prototype.isPrototypeOf(person2));
log(Object.getPropertyOf(person2) == Person.property)
原型属性的检测:
hasOwnProperty()
检测一个属性是否存在实例中,还是存在原型中。,只有存在实例中的属性才会返回true。(注意:当实例重写了原型属性后就变成了实例属性,这个时候也会返回true。)
function Person(){
}
Person.prototype.name = 'Nicholas';
let person = new Person();
log(person1.hasOwnProperty('name')) //false
person1.name = 'Greg';
log(person1.hasOwnProperty('name')) //true (name来自实例)
delete person1.name;
log(person1.hasOwnProperty('name')) //false (name来自原型)
in 操作符
单独使用in操作符会在通过对象能够访问给定属性时返回true,不论该属性是在原型中还是实例中。
log('name' in person1);