標籤: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