理解prototype

1. 每定義一個函數,會自動創建一個prototype屬性

function Person() {};
alert(Person.prototype); //[Object]
Person.prototype.name = "Jeff";
Person.prototype.job = "Worker";


2. prototype會自動創建一個constructor的屬性,constructor又指向了prototype所在的類。

alert(Person.prototype.constructor);//function Person(){};


3. 創建的實例包含了一個屬性:__proto__(不是所以瀏覽器都支持這個屬性),它指向了prototype

var person1 = new Person();
alert(person1.__proto__); //[Object]
alert(person1.__proto__.constructor); //function Person(){}
alert(person1.__proto__.constructor == Person.prototype.constructor);// true;


參考資料: 《JavaScript高級程序設計》 6.1.3 原型模式


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章