typeof {} // object
使用 instanceof 就是判断一个实例是否属于某种类型。数组
const b = {}; console.log(a instanceof Object); //true
更重要的一点是 instanceof 能够在继承关系中用来判断一个实例是否属于它的父类型。函数
console.log(Object instanceof Object); //true console.log(Function instanceof Function); //true console.log(Number instanceof Number); //false console.log(String instanceof String); //false console.log(Function instanceof Object); //true console.log(Foo instanceof Function); //true console.log(Foo instanceof Foo); //false
比较自定义对象this
function Foo() {} function Bar() {} Bar.prototype = new Foo(); new Bar() instanceof Bar; // true new Bar() instanceof Foo; // true // 若是仅仅设置 Bar.prototype 为函数 Foo 自己,而不是 Foo 构造函数的一个实例。 Bar.prototype = Foo; new Bar() instanceof Foo; // false
instanceof 比较内置类型
可是,不是经过构造函数建立的对象使用instanceof比较,那获得的,可能就不是你想要的结果。prototype
new String('foo') instanceof String; // true new String('foo') instanceof Object; // true 'foo' instanceof String; // false 'foo' instanceof Object; // false
const o = {}; console.log(o.constructor); //function Object(){ [native code] }
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
Let O be the result of calling ToObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
const b = {0:'Hello',1:'Howard'}; const c = 'Hello Howard'; Object.prototype.toString.call(b); //"[object Object]" Object.prototype.toString.call(c); //"[object String]"
const a = []; console.log(a instanceof Array); //true
实例化的数组拥有一个constructor属性,这个属性指向生成这个数组的方法。code
const a = []; console.log(a.constructor); //function Array(){ [native code] }
constructor属性是能够改写的,若是更改,那么使用这种方法就没法判断出是否为数组了
const a = ['Hello','Howard']; Object.prototype.toString.call(a); //"[object Array]"
const a = []; const b = {}; Array.isArray(a);//true Array.isArray(b);//false
修改constructor对象:对象
const a = []; const b = {}; a.constructor = b.constructor; Array.isArray(a); //true
Object.getPrototypeOf(a) === Array.prototype;
function isEmptyObject(obj){ for (var key in person) { if (person.hasOwnProperty(key)) { return false; } } return true; };
var data = {}; JSON.stringify(data) == "{}" //true
var data = {}; var arr = Object.getOwnPropertyNames(data); console.log(arr.length == 0); //true
var data = {}; var arr = Object.keys(data); console.log(arr.length == 0); //true