目录
typeof
缺点: 无法区分 null
还是 object
,因为 typeof null
的值为 object
typeof undefined // 'undefined'
typeof '10' // 'string'
typeof 10 // 'number'
typeof false // 'boolean'
typeof Symbol() // 'symbol'
typeof Function // 'function'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
Q:为什么typeof null
值为 object
?
A:因为在JavaScript中,不同的对象都是使用二进制存储的,如果二进制前三位都是0的话,系统会判断为是Object类型,而null的二进制全是0,自然也就判断为Object。这个bug是初版本的JavaScript中留下的,
instanceof
缺点:只能判断对象是否存在于目标对象的原型链上
function Foo() { }
var f1 = new Foo();
var d = new Number(1)
console.log(f1 instanceof Foo); // true
console.log(d instanceof Number); //true
console.log(123 instanceof Number); //false -->不能判断字面量的基本数据类型
// instanceof判断一个对象是否是另一个对象的实例,而数字123是基本数据类型,不是对象,
instanceof 原理
instanceof原理实际上就是查找目标对象的原型链
// L代表instanceof左边,R代表右边
function myInstanceof(L, R) {
let LP = L.__proto__;
let RP = R.prototype;
while(true) {
if(LP === RP) {
return true;
}
if(LP === null) {
return false;
}
LP = LP.__proto__;
}
}
myInstanceof({}, Object) // true
constructor
var d = new Number(1)
var e = 1
function fn() {}
var date = new Date();
var arr = [1, 2, 3];
var reg = /[hbc]at/gi;
console.log(e.constructor);//ƒ Number() { [native code] }
console.log(e.constructor.name);//Number
console.log(d.constructor.name);//Number
console.log(fn.constructor.name) // Function
console.log(date.constructor.name)// Date
console.log(arr.constructor.name) // Array
console.log(reg.constructor.name) // RegExp
Object.prototype.toString.call()
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call(123)); // "[object Number]"
console.log(Object.prototype.toString.call("abc")); // "[object String]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"
console.log(Object.prototype.toString.call([])); // "[object Array]"
function fn() {}
var date = new Date();
var arr = [1, 2, 3];
var reg = /[hbc]at/gi;
console.log(Object.prototype.toString.call(fn));// "[object Function]"
console.log(Object.prototype.toString.call(date));// "[object Date]"
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(reg));// "[object RegExp]"
为什么 Object.prototype.toString.call(null) 输出为 “[object Null]” ?
toString() 是 Object的原型方法,调用该方法默认返回当前对象的 [[Class]]。这是一个内部属性,其格式为 [[Object Xxx]],其中 Xxx 就是对象的类型。
JavaScript万物皆对象,为什么 xxx.toString() 不能返回变量类型?
这是因为各个类中重写了 toString 的方法,因此要调用Object 中的 toString 方法,必须使用 toString.call() 的方式调用。对于Object 对象,可以直接调用toString() 就能返回 “[[Object Object]]”,而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型。