js定義對象

來源:互聯網
上載者:User

標籤:name   執行函數   win   原廠模式   ons   call   cti   var   bsp   

1.原廠模式

function createPerson(name,age,job){ 
var o = {}; 
o.name = name; 
o.age = age; 
o.job = job; 
o.sayName = function(){ 
alert(this.name); 
}; 
return o; 

var tanya = createPerson("tanya","30","female"); 
var ansel = createPerson("ansel","30","male"); 
tanya.sayName(); 
ansel.sayName(); 

這裡先定義o為一個空的對象,然後為o設定了一堆屬性。其實也可以直接給o屬性的嘛,所以如果這樣寫也是ok的。 

function createPerson(name,age,job){ 
var o = { 
name : name, 
age : age, 
job : job, 
sayName : function(){ 
alert(this.name); 

}; 
return o; 

var tanya = createPerson("tanya","30","female"); 
var ansel = createPerson("ansel","30","male"); 
tanya.sayName(); 
ansel.sayName(); 

 

2.建構函式模式 

unction Person(name,age,job){ 
this.name = name; 
this.age = age; 
this.job = job; 
this.sayName = function(){ 
alert(this.name); 
}; 

var tanya = new Person("tanya","30","female"); 
var ansel = new Person("ansel","30","male"); 
tanya.sayName(); 
ansel.sayName(); 

在這個例子中,tanya和ansel都有一個constructor屬性,該屬性指向person。 
考慮一下如下的情況: 

function Person(name,age,job){ 
this.name = name; 
this.age = age; 
this.job = job; 
this.sayName = function(){ 
alert(this.name); 
}; 

Person("tanya","30","female"); 
Person("ansel","30","male"); 
window.sayName(); 
window.sayName(); 

發現兩次彈出的都是ansel,這是因為不用new的話,就不是一個person的執行個體,而僅僅在執行函數。而在全域範圍調用一個函數時this總是指向Global對象。而Global對象在瀏覽器中就是window對象。 

我們還可以用構造模式在另外一個對象中調用sayName方法,還記得Apply和call麼,來吧再考慮另外一種情況, 

function Person(name,age,job){ 
this.name = name; 
this.age = age; 
this.job = job; 
this.sayName = function(){ 
alert(this.name); 
}; 

var olivia = {}; 
Person.call(olivia,"tanya","30","female"); 
olivia.sayName(); 
var philip = {} 
Person.apply(philip,["ansel","30","male"]); 
philip.sayName(); 

原型模式就要考慮原型鏈了,分析一下,sayName方法在執行個體中被重複定義了兩次,但其實沒有必要創造兩個一樣的副本。使用原型方法,可以使是tanya和ansel的共用一個sayName方法。 
於是原型模式的寫法如下: 

function Person(name,age,job){ 
this.name = name; 
this.age = age; 
this.job = job; 

Person.prototype.sayName= function(){ 
alert(this.name); 
}; 
var tanya = new Person("tanya","30","female"); 
var ansel = new Person("ansel","30","male"); 
tanya.sayName(); 
ansel.sayName(); 

js定義對象

聯繫我們

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