//使用this關鍵字定義構造的上下文屬性 function Girl() { this.name = "big pig"; this.age = 20; this.standing; this.bust; this.waist; this.hip; } //使用prototype function Girl(){} Girl.prototype.name = "big pig"; Girl.prototype.age = 20; Girl.prototype.standing; Girl.prototype.bust; Girl.prototype.waist; Girl.prototype.hip; alert(new Girl().name);
上例中的兩種定義在本質上沒有區別,都是定義“Girl”對象的屬性信息。“this”與“prototype”的區別主要在于屬性訪問的順序。如:
function Test() { this.text = function() { alert("defined by this"); } } Test.prototype.test = function() { alert("defined by prototype"); } var _o = new Test(); _o.test();//
當訪問對象的屬性或者方法是,將按照搜索原型鏈prototype chain的規則進行。首先查找自身的靜態屬性、方法,繼而查找構造上下文的可訪問屬性、方法,最后查找構造的原型鏈。
“this”與“prototype”定義的另一個不同點是屬性的占用空間不同。使用“this”關鍵字,示例初始化時為每個實例開辟構造方法所包含的所有屬性、方法所需的空間,而使用“prototype”定義,由于“prototype”實際上是指向父級的一種引用,僅僅是個數據的副本,因此在初始化及存儲上都比“this”節約資源。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com