標籤:type 產生 on() rip 工廠 name 組合 javascrip 好的
有三種基本的方式可以建立對象: 原廠模式、建構函式模式和原型模式
原廠模式:
function createPerson(name, age) { var o = new Object(); o.name = name; o.age = age; o.getName = function() { alert(this.name); }; return o; }var person1 = createPerson(‘james‘, 18);
構造模式
function Person(name, age) {this.name = name;this.age = age;this.sayName = function() {alert(this.name);};}var person1 = new Person(‘james‘, 18);
原型模式
function Person() {}; Person.prototype.name = ‘james‘; Person.prototype.age = 18; Person.prototype.getName = function() { alert(this.name);};var person1 = new Person();
理解原型對象:
當定義建構函式Person時,會自動產生一個Person的原型對象Person.prototype;
Person.prototype中同時自動產生屬性constructor指向Person;
注意: 如果用對象字面量重新定義原型對象時,需要添加屬性constructor指向建構函式;
原廠模式每次都會生產出一個執行個體返回,類和封裝的實現沒有達到;
建構函式模式每次建立一個執行個體,其中的共通方法(函數)都會產生一個新的執行個體;
原型模式未實現每個執行個體得私人屬性;
因此,最好的建立對象的模式為:
組合使用建構函式模式和原型模式
function Person(name, age) { this.name = name; this.age = age; this.friends = [];}Person.prototype = { constructor: Person, sayName: function() { alert(this.name); }};var Person1 = new Person(‘james‘, 18);
JavaScript 建立對象