建立對象:瀏覽器
var person = new Obejct(); person.name = 'sun'; person.sayName = function(){ alert(this.name); //this.name將被解析爲person.name }
對象字面量語法:可是當須要建立多個對象時,會產生大量重複的代碼:函數
var person = { name : 'sun', age : 11, sayName : function(){ alert(this.name); } }
工廠模式:用函數來封裝特定對象的建立細節this
function createPerson(name, age){ var p = new Object(); p.name = name; p.age = age; p.sayName = function(){ alert(this.name); }; return p; } var person1 = createPerson("sun", 13);
問題:沒有解決對象識別問題(不能知道對象的類型)。spa
構造函數模式:prototype
function Person(name, age){ this.name = name; this.age = age; this.sayName = function(){ alert(this.name); }; } var person1 = new Person("sun",12); alert(person1.constructor);
1:再也不顯示的建立對象指針
2:直接將屬性和方法賦值給this對象code
3:沒有return語句對象
構造函數模式的問題:每一個方法都要在每一個實例上春心建立一遍。ip
解決這個問題的簡單方法——把函數的定義轉移到構造函數外部。原型
下面例子中全部對象實例將共享一個全局的函數,函數sayName被調用時,經過this綁定執行環境中的Person對象
function Person(name){ this.name = name; this.sayName = sayName;//指針 } function sayName(){ alert(this.name); }
新問題:若是須要定義多個方法,就要定義多個全局函數。且此方法破壞了新對象類型的封裝性。
原型模式:
每一個函數都有一個原型屬性:prototype,它是一個指針,指向一個對象。這個對象的用途是:包含特定類型的全部實例共享的屬性和方法。
使用原型對象的好處:讓全部對象實例共享它所包含的屬性和方法。
function Person(){} Person.prototype.name = 'sun'; Person.prototype.age = 18; Person.prototype.sayName = function(){ alert(this.name); }; var person1 = new Person(); alert(person1.name); //sun var person2 = new Person(); alert(person2.name); //sun alert(person1.sayName == person2.sayName); //true,同一個方法
每建立一個函數,就會同時建立他的prototype對象,這個對象也會自動擁有一個constructor屬性指向函數自己。
更簡單的原型模式: 原型+對象字面量
function Person(){} Person.prototype = { //constructor : Person, name : 'sun', age : 15, job : '...', sayName : function(){ alert(this.name); } };
注意:此時constructor屬性不在指向Person。
這種語法的本質:徹底重寫了默認的prototype對象,這個對象也會自動得到一個constructor屬性,這個constructor指向Object構造函數,
若是constructor真的很重要,能夠像上面註釋掉的那樣,顯式的生命constructor
但這個constructor是可枚舉的,默認的constructor是不可枚舉的,所以能夠使用下列方法設置。
(該方式僅適用於兼容ECMAScript5的瀏覽器)
Object.defineProperty(Person.prototype, "constructor", { enumerable : false ; //不可枚舉 value : Person });
原型模式的問題:prototype中的屬性值若是是引用類型,會被全部對象實例共享。
組合使用構造函數模式和原型模式:
構造函數模式用於定義實例的屬性,原型模式用於定義方法和共享的屬性。
function Person(name, age){ this.name = name; this.age = age; this.friends = ["sun","cheng"]; } Person.prototype = { constructor : Person, sayName : function(){ alert(this.name); } }