instanceof
运算符用来检测 constructor.prototype
是否存在于参数 object
的原型链
instanceof
function Car(){}var car = new Car()function Person(){}var person = new Person()console.log(car instanceof Car) // trueconsole.log(car instanceof Object) // trueconsole.log([] instanceof Array) // trueconsole.log({} instanceof Object) // true复制代码
-
封装
typeOf
方法function myTypeOf(val) { var toStr = Object.prototype.toString; var type = typeof(val); var res = { '[object Array]': 'object array', '[object Object]': 'object object', '[object Number]': 'object number', '[object String]': 'object string', '[object Boolean]': 'object boolean' } if (type == null) { return 'null'; } else if (type == 'object') { var ret = toStr.call(val) return res[ret]; } else { return type; } }复制代码