javascript設計模式:構造器模式學習一

 javascript 設計模式
1、簡介
javascript是一種弱類型語言,不過類可以通過函數模擬出來
最常見的實現方法如下:
function Car(model)
{
this.model = model;
this.color = "red";
this.year = "2012";
this.getInfo = function(){
return this.model + " " + this.year;
}
}
接下來我們可以使用上邊定義Car構造實例化對象,就像這樣:
var myCar = new Car("hello");
myCar.year = "2015";
console.log(myCar.getInfo());

 

2、構造器模式
(1)創建對象的三種方法
var newObject = {};
var newObject = Object.create(null);
var newObject = new Object();
(2)四種方式可以將一個鍵值複製給對象
1)“點號”法
設置屬性:newObject.someKey = "hello world";
獲取屬性:var key = newObject.someKey;
2)"方括號"法
設置屬性:newObject["someKey"] = "hello world";
獲取屬性:var key = newObject["someKey"];

(3)使用原型構造器
function Car(model,year,miles){
this.model = model;
this.year = year;
this.miles = miles;
}
Car.prototype.toString = funtion(){
return this.model + "has done "+ this.miles;
}
通過上邊的代碼,單個toString()實例被所以的Car對象所共享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章