js中的prototype

來源:互聯網
上載者:User

標籤:ima   object   nbsp   span   變數   ack   prot   執行個體   ati   

參考文獻:阮一峰的部落格

  http://www.ruanyifeng.com/blog/2011/06/designing_ideas_of_inheritance_mechanism_in_javascript.html

  http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html

1、為什麼會出現prototype

  Every JavaScript object has a prototype. The prototype is also an object.All JavaScript objects inherit their properties and methods from their prototype.所有的js對象都有一個prototype,這個prototype也是一個對象。

  在使用建構函式模式,執行個體對象時。對於不變的屬性和方法,要放在prototype屬性上,這樣他們在記憶體中只產生一次。如果是都放在中,沒產生一個執行個體就多產生一次,多佔用記憶體。

  因此,在prototype中存放的是不變的屬性以及方法。

2、建構函式建立對象的方式

        function Person(name, age) {            this.name = name;            this.age = age;        }        //prototype放各執行個體共用的變數、方法        Person.prototype = {            des: "人類",            eat: function () {                console.log(‘eat‘);            }        }        var person1 = new Person("person1", 12);        person1.eat();        console.log(person1.des);        console.log(person1.name);        console.log(person1.age);    

   運行:

  

 

js中的prototype

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.