1、通過JSON建立對象
2、先new Object,然後添加屬性和方法,缺點:會產生大量重複的代碼
var people = new OBject();people.name = "aaaa";people.getName = function(){ alert('get the name:' +this.name);}
3、通過對象字面量,缺點:會產生大量重複的代碼
var people = { name: "aaaa", getName: function(){ alert('get the name:'+this.name); }}
4、原廠模式,缺點:不能識別對象的類型
function createFunction(name){ var o = new Object(); o.name = name; o.getName = function(){ alert('get the name: '+this.name); }
return o;}
5、建構函式模式,缺點:不能實現方法的共用
function People(name){ this.name = name; this.getName = function(){ alert('get the name '+this.name); }}
6、原型模式,缺點:有些屬性不需要共用
var Peopel = {}People.prototype = { constructor:People, name:"aaa", getName:function(){ alert('the name is:' +this.name); }}
7、組合使用建構函式模式和原型模式
function People(name){ this.name = name;}People.prototype = { constructor:People; getName: function(){ alert('the name is'+this.name); }}
8、動態原型模式,這是一種較好的建立對象模式
1 function People(name){2 this.name = name;3 if(typeof this.getName != "function"){4 People.prototype.getName = function(){5 alert('the name is:' +this.name);6 }7 }8 }