typeof
只适用与基本类型
1 console.log(typeof "langshen"); // String
2 console.log(typeof 666); // Number
3 console.log(typeof true); // Boolean
4 console.log(typeof false); // Boolean
5 console.log(typeof function(){}); // Function
6 console.log(typeof undefined); // Undefined
7 console.log(typeof null); // Object
8 console.log(typeof []); // Object
9 console.log(typeof {}); // Object
10. console.log(type NaN) //Number
使用场景
可以用来检测函数是否传值
1 function fn(a, b) {
2 if (typeof b === "undefined") { // 没有传递参数
3 b = 0;
4 }
5 console.log(a, b); //1 0
6 }
7 fn(1);
instanceof 检测一个实例是不是属于某个类
instanceof 可以正确的判断对象的类型
因为内部机制是通过判断对象的原型链中是不是能找到类型的 prototype。
instanceof是一个操作符,返回值是一个布尔值
instanceof是检测引用数据类型,而不能检测基本数据类型
console.log("langshen" instanceof String); //false
console.log(666 instanceof Number); //false
console.log(true instanceof Boolean); //false
console.log([] instanceof Array); //true
console.log([] instanceof Object); //true
console.log(function(){} instanceof Function); //true
console.log({} instanceof Object); //true
只由new出来的才返回true
1 new String("langshen") instanceof String //true
2 new Number(666) instanceof Number //true
3 new Boolean(true) instanceof Boolean //true
constructor
constructor这个属性存在于构造函数的原型上,指向构造函数,
对象可以通过 proto 在其所属类的原型上找到这个属性
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就会变得不可靠了
看着好像很完美,但是
所有对象都会从它的原型上继承一个 constructor 属性
function Fn(){};
Fn.prototype=new Array();
var f=new Fn();
console.log(f instanceof Fn) true
console.log(f instanceof Object) true
console.log(f instanceof Array) true
console.log(f.constructor===Fn); //false
console.log(f.constructor===Array); // true
Object.prototype.toString.call()
console.log(Object.prototype.toString.call(1)); //[object Number]
console.log(Object.prototype.toString.call('')); //[object String]
console.log(Object.prototype.toString.call(true)); //[object Boolean]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call(undefined)); //[object Undefined]
console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call({})); // [object Object]
console.log(Object.prototype.toString.call(/^$/)); //[object RegExp]
console.log(Object.prototype.toString.call((function () {}))); //[object Function]