Javascript:原型模式類繼承

來源:互聯網
上載者:User

標籤:

原型模式每個函數(準確說不是類、對象)都有一個prototype屬性,這個屬性是一個指標,指向一個對象。使用原型對象的好處是可以讓所有對象執行個體共用它包含的屬性和方法。 1.原型對象(1)當建立一個新函數,就會為該函數建立一個prototype屬性,這個屬性指向函數的原型對象。(2)預設情況下,所有原型對象都會自動獲得一個constructor(建構函式)屬性,這個屬性包含一個指向 prototype屬性所在函數  的指標。(3)執行個體的內部包含一個指標,叫[[Prototype]]。不過這個指標對指令碼則完全不可見(某些瀏覽器支援一種__proto__來訪問)。 2.代碼讀取屬性順序 首先搜尋對象執行個體本身,沒有則繼續搜尋指標指向的原型對象。例:  function Person(){  }  Person.prototype.name="Javascript";  var p1 = new Person();  var p2 = new Person();    p1.name="lufeng";  alert(p1.name);//"lufeng"  alert(p2.name);//"Javascript"    使用delete操作符可以完全刪除執行個體屬性。  isPrototypeOf():確定對象之間是否存在prototype關係hasOwnProperty():檢測一個屬性是存在於執行個體中,還是存在原型中。Object.keys()、Object.getOwnPropertyNames():接收一個對象作為參數,返回 一個包含所有可枚舉屬性的字串數組。  來看個很蛋疼的類繼承(某個HTML5遊戲架構):               inherit : function(childClass, parentClass) {            var Constructor = new Function();            Constructor.prototype = parentClass.prototype;            childClass.prototype = new Constructor();            childClass.prototype.constructor = childClass;            childClass.superclass = parentClass.prototype;             if(childClass.prototype.constructor == Object.prototype.constructor) {                childClass.prototype.constructor = parentClass;            }        }感覺代碼看來比較亂,我畫了個圖:

Javascript:原型模式類繼承

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.