關於javascript原型鏈的記錄

赤島發表於2018-11-05

建構函式擁有名為prototype屬性,每個物件都擁有__proto__屬性,而且每個物件的__proto__屬性指向自身建構函式prototype。
**當呼叫某種方法或屬性時,首先會在自身呼叫或查詢,如果自身沒有該屬性或者方法,則會去它的__proto__屬性中呼叫查詢,也就是它建構函式的prototype中呼叫查詢**;

function Person(){}
var person = new Person();
console.log(person.__proto__==Person.prototype);      //true
console.log(Person.__proto__==Function.prototype);    //true
console.log(String.__proto__==Function.prototype);    //true
console.log(Number.__proto__==Function.prototype);    //true
console.log(JSON.__proto__==Function.prototype);      //false
console.log(JSON.__proto__==Object.prototype);        //true
console.log(Math.__proto__==Object.prototype);        //true
console.log(Function.__proto__==Function.prototype);  //true

因為建構函式.prototype也是物件(稱之為原型物件),因此也具有__proto__方法,所有的建構函式的原型物件都指向Object.prototype(除了Object.prototype自身);
console.log(Person.prototype.__proto__==Object.prototype); //true
console.log(Object.prototype.__proto__==null); //true

相關文章