javascript對象的幾種建立方式

來源:互聯網
上載者:User

標籤:ret   reg   需要   font   建立對象   12px   func   pos   加工   

javascript對象的幾種建立方式1、原廠模式

其作用是利用物件導向的方法,把一些對象封裝,使一些佔用空間多的,重複的代碼封裝起來

//缺點1.建構函式的時候是需要new的

//2.重複定義的函數

function createPerson(name,age){//js建立對象的原廠模式
var obj=new Object();//原料
obj.name=name;
obj.age=age;

obj.showName=function(){
alert("名字是"+this.name);
}
obj.showAge=function(){
alert("年齡"+this.age);
}//加工的過程
return obj;//成品
}
// var date=new Date();
// var re=new RegExp();

var obj2=createPerson("zjk",29);
// obj2.showName();
// obj2.showAge();
var obj3=createPerson("zjk1",39);
// obj3.showName();
// obj3.showAge();
alert(obj2.showName==obj3.showName);

 

2、建構函式模式

CMAScript中的建構函式可以用來建立特定類型的對象,也可以建立自訂的建構函式,從而自訂物件類型的屬性和方法

function ceratePerson(name,age){
this.name=name;
this.age=age;
this.showName=function(){
alert("我的名字是:"+this.name);
}
this.showAge=function(){
alert("我的名字是:"+this.age);
}
}
var obj = new ceratePerson("李四", 30);
console.log(obj.name);
obj.showName();

 

javascript對象的幾種建立方式

聯繫我們

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