JS設計模式 建構函式模式(2)

2022-06-16 22:27:09 字數 2251 閱讀 6202

function

car(model, year, miles) ;

}var tom= new car("大叔", 2009, 20000);

var dudu= new car("dudu", 2010, 5000);

console.log(tom.output());

console.log(dudu.output());

問題是output()在每次建立物件的時候都重新定義了,沒有共享。

可以用如下方式:

function

car(model, year, miles)

function

formatcar()

更好的方式,使用原型繼承output方法:

function

car(model, year, miles)

/*注意:這裡我們使用了object.prototype.方法名,而不是object.prototype

主要是用來避免重寫定義原型prototype物件

*/car.prototype.output= function

() ;

var tom = new car("大叔", 2009, 20000);

var dudu = new car("dudu", 2010, 5000);

console.log(tom.output());

console.log(dudu.output());

function

car(model, year, 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()會正確輸出結果,而如果使用new關鍵字則沒有這個問題。

//

使用new 關鍵字

var tom = new car("大叔", 2009, 20000);

console.log(

typeof tom); //

"object"

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

"大叔走了20000公里"

function

car(model, year, miles)

this.model =model;

this.year =year;

this.miles =miles;

this.output = function

() }

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還是繼續執行**,如果使用的是new關鍵字,則(this instanceof car)為真,會繼續執行下面的引數賦值,如果沒有用new,(this instanceof car)就為假,就會重新new乙個例項返回。

建構函式模式

已經n天沒有學習了。中間辦了好多事,關乎人生大事,所以斷了學習。貌似理由很充分。總之,今天是十一長假的第二天,沒打算出去玩,把前段時間沒學習的趕緊彌補一下吧。上回說到建立物件時用的工廠模式,減少了 重複,可是不能區分出每個例項所對應的物件,於是建構函式登場了。function createobjec...

建構函式模式

function student props student.prototype.hello function function createstudent props var xiaoming createstudent xiaoming.hello hello xiaoming 傳進乙個陣列 f...

JS中的工廠模式和建構函式模式

工廠方法建立物件 function createperson name age gender return obj var obj2 createperson 豬八戒 18 男 var obj3 createperson 孫悟空 18 男 obj2.say 豬八戒 obj3.say 孫悟空使用工廠方...