深刻理解JavaScript系列(26):設計模式之構造函數模式

介紹

構造函數你們都很是熟悉了。只是假設你是新手。仍是有必要來了解一下什麼叫構造函數的。構造函數用於建立特定類型的對象——不只聲明瞭使用的對象,構造函數還可以接受參數以便第一次建立對象的時候設置對象的成員值。你可以本身定義本身的構造函數。而後在裏面聲明本身定義類型對象的屬性或方法。函數

基本使用方法

在JavaScript裏,構造函數通常是以爲用來實現實例的。JavaScript沒有類的概念,但是有特殊的構造函數。經過newkeyword來調用定義的否早函數。你可以告訴JavaScript你要建立一個新對象並且新對象的成員聲明都是構造函數裏定義的。在構造函數內部,thiskeyword引用的是新建立的對象。基本使用方法例如如下:post

function Car(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
    this.output= function () {
        return this.model + "走了" + this.miles + "千米";
    };
}

var tom= new Car("大叔", 2009, 20000);
var dudu= new Car("Dudu", 2010, 5000);

console.log(tom.output());
console.log(dudu.output());

上面的樣例是個很是easy的構造函數模式,但是有點小問題。this

首先是使用繼承很是麻煩了。其次output()在每次建立對象的時候都又一次定義了,最好的方法是讓所有Car類型的實例都共享這個output()方法,這樣假設有大批量的實例的話。就會節約很是多內存。spa

解決問題,咱們可以使用例如如下方式:prototype

function Car(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
    this.output= formatCar;
}

function formatCar() {
    return this.model + "走了" + this.miles + "千米";
}

這個方式儘管可用。但是咱們有例如如下更好的方式。code

構造函數與原型

JavaScript裏函數有個原型屬性叫prototype,當調用構造函數建立對象的時候,所有該構造函數原型的屬性在新建立對象上均可用。orm

依照這樣,多個Car對象實例可以共享同一個原型,咱們再擴展一下上例的代碼:對象

function Car(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
}

/*
注意:這裏咱們使用了Object.prototype.方法名,而不是Object.prototype
主要是用來避免重寫定義原型prototype對象
*/
Car.prototype.output= function () {
    return this.model + "走了" + this.miles + "千米";
};

var tom = new Car("大叔", 2009, 20000);
var dudu = new Car("Dudu", 2010, 5000);

console.log(tom.output());
console.log(dudu.output());

這裏。output()單實例可以在所有Car對象實例裏共享使用。blog

另外:咱們推薦構造函數以大寫字母開頭,以便區分普通的函數。繼承

僅僅能用new嗎?

上面的樣例對函數car都是用new來建立對象的。僅僅有這一種方式麼?事實上還有別的方式,咱們列舉兩種:

function Car(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
    // 本身定義一個output輸出內容
    this.output = function () {
        return this.model + "走了" + this.miles + "千米";
    }
}

//方法1:做爲函數調用
Car("大叔", 2009, 20000);  //加入到window對象上
console.log(window.output());

//方法2:在另一個對象的做用域內調用
var o = new Object();
Car.call(o, "Dudu", 2010, 5000);
console.log(o.output()); 

該代碼的方法1有點特殊,假設不適用new直接調用函數的話,this指向的是全局對象window,咱們來驗證一下:

//做爲函數調用
var tom = Car("大叔", 2009, 20000);
console.log(typeof tom); // "undefined"
console.log(window.output()); // "大叔走了20000千米"

這時候對象tom是undefined。而window.output()會正確輸出結果,而假設使用newkeyword則沒有這個問題,驗證例如如下:

//使用new keyword
var tom = new Car("大叔", 2009, 20000);
console.log(typeof tom); // "object"
console.log(tom.output()); // "大叔走了20000千米"

強制使用new

上述的樣例展現了不使用new的問題。那麼咱們有沒有辦法讓構造函數強制使用newkeyword呢,答案是確定的,上代碼:

function Car(model, year, miles) {
    if (!(this instanceof Car)) {
        return new Car(model, year, miles);
    }
    this.model = model;
    this.year = year;
    this.miles = miles;
    this.output = function () {
        return this.model + "走了" + this.miles + "千米";
    }
}

var tom = new Car("大叔", 2009, 20000);
var dudu = Car("Dudu", 2010, 5000);

console.log(typeof tom); // "object"
console.log(tom.output()); // "大叔走了20000千米"
console.log(typeof dudu); // "object"
console.log(dudu.output()); // "Dudu走了5000千米"

經過推斷this的instanceof是否是Car來決定返回new Car仍是繼續運行代碼,假設使用的是newkeyword,則(this instanceof Car)爲真,會繼續運行如下的參數賦值。假設沒實用new,(this instanceof Car)就爲假。就會又一次new一個實例返回。

原始包裝函數

JavaScript裏有3中原始包裝函數:number, string, boolean,有時候兩種都用:

// 使用原始包裝函數
var s = new String("my string");
var n = new Number(101);
var b = new Boolean(true);


// 推薦這樣的
var s = "my string";
var n = 101;
var b = true;

推薦,僅僅有在想保留數值狀態的時候使用這些包裝函數。關於差異可以參考如下的代碼:

// 原始string
var greet = "Hello there";
// 使用split()方法切割
greet.split(' ')[0]; // "Hello"
// 給原始類型加入新屬性不會報錯
greet.smile = true;
// 單無法獲取這個值(18章ECMAScript實現裏咱們講了爲何)
console.log(typeof greet.smile); // "undefined"

// 原始string var greet = new String("Hello there"); // 使用split()方法切割 greet.split(' ')[0]; // "Hello" // 給包裝函數類型加入新屬性不會報錯 greet.smile = true; // 可以正常訪問新屬性 console.log(typeof greet.smile); // "boolean"

總結

本章主要解說了構造函數模式的用法、調用方法以及newkeyword的差異,但願你們在使用的時候有所注意。

相關文章
相關標籤/搜索