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