javascript之創建對象
學過面向對象編程的同學一定都知道,類是對象的模板,對象是根據模板創建的。
可是Javascript中沒有類的概念,只有對象的概念,沒有類怎么創建對象呢?
下面介紹兩種創建javascript對象方法:
- 直接賦值法
- 構造函數法
直接賦值法
var shopProduct = {
title:'上衣', // 對象的屬性
"brand":"優衣庫",
'price':300, //key可以加引號或者雙引號。
getSunmary:function(){ //對象的方法
return "titile: "+this.title+", brand: "+this.brand+", price: "+this.price;
}
}
// 輸出對象屬性
console.log(shopProduct.title);
console.log(shopProduct.price);
console.log(shopProduct.brand);
構造函數法
先定義一個函數,然后用關鍵字new調用它,就會得到一個對象。
function ShopProduct(name,brand,price)
{
this.name =name;
this.brand= brand;
this.price = price;
this.getSunmary = function(){
return "titile: "+this.name+", brand: "+this.brand+", price: "+this.price;
};
return this;
}
shoes = new ShopProduct('shoes','nike',500);
console.log(shoes.name);
console.log(shoes.price);
console.log(shoes.brand);
console.log(shoes.getSunmary());
注意:
- 構造函數中的this指向新對象。
- 構造函數中雖然沒有return,但是默認返回this。