以前每件事都差很少,直到如今才發現差不少。如今才發現理清一件事的原委是多麼快樂的一件事,咱們共同勉勵。javascript
懶得扯淡,直接正題java
不基於例子的講原理都是扯淡,知乎同樣的舉例都是賣弄函數
function A () { }; A.prototype = { }; function B () { }; var a = new A(); B.prototype = new A(); var b = new B(); console.log(a.constructor); //Object console.log(A.constructor); //Function console.log(a.hasOwnProperty('constructor')); // false console.log(A.hasOwnProperty('constructor')); // false console.log(a instanceof A); // true console.log(b.constructor); // Object console.log(B.constructor); // Function console.log(b.hasOwnProperty('constructor')); // false console.log(B.hasOwnProperty('constructor')); // false console.log(b instanceof B); // true console.log(b instanceof A); // true
console.log(a.constructor); //Object console.log(A.constructor); //Function console.log(b.constructor); // Object console.log(B.constructor); // Function
首先須要明確 constructor 屬性是 Object.prototype 對象上的, Object.prototype.hasOwnProperty('constructor') === true,而實例對象上的 constructor 屬性是從其原型鏈中取。spa
object instanceof constructor # 參數 - object 檢測的對象 - constructor 構造函數
檢測 constructor.prototype 是否存在於object的原型鏈上prototype
# 此處爲文章前面的例子,只是把對於 instanceof 的判斷集中起來 console.log(a instanceof A); // true console.log(b instanceof B); // true console.log(b instanceof A); // true
看 MDN instanceof有下面的例子(精簡化)code
function C(){} var o = new C(); o instanceof C; // true,由於 Object.getPrototypeOf(o) === C.prototype o instanceof Object; // true,由於Object.prototype.isPrototypeOf(o)返回true C.prototype instanceof Object // true,同上 C.prototype = {}; var o2 = new C(); o2 instanceof C; // true o instanceof C; // false,C.prototype指向了一個空對象,這個空對象不在o的原型鏈上.
乍一看,上面的例子,始終對於最後 o instanceof C 返回 false 不理解,其實只要明白 object.__proto__ 和 Constructor.prototype 是兩個引用值,在使用 Constructor 建立實例 object 時, object.__proto__ === Constructor.prototype,以後 object.__proto__ 改變和 Constructor.prototype 任意其一改變都會致使最後 object.__proto__ !== Constructor.prototype對象
console.log(a.hasOwnProperty('constructor')); // false console.log(A.hasOwnProperty('constructor')); // false console.log(b.hasOwnProperty('constructor')); // false console.log(B.hasOwnProperty('constructor')); // false
constructor 屬性是從原型對象上繼承的blog
MDN instanceof
MDN constructor
MDN hasOwnProperty
MDN Prototype繼承