第一種方式:
為了保證構(gòu)造函數(shù)必須與new命令一起使用,一個(gè)解決辦法是,在構(gòu)造函數(shù)內(nèi)部使用嚴(yán)格模式,即第一行加上use strict。
function Fubar(foo, bar){
'use strict';
this._foo = foo;
this._bar = bar;
}
Fubar()
// TypeError: Cannot set property '_foo' of undefined
第二種方式:
是在構(gòu)造函數(shù)內(nèi)部判斷是否使用new命令,如果發(fā)現(xiàn)沒(méi)有使用,則直接返回一個(gè)實(shí)例對(duì)象。
function Fubar( foo,bar){
if( !(this instanceof Fubar)){
return new Fubar( foo,bar)
}
this._foo=foo;
this._bar=bar;
}
Fubar( 1,3)._foo //1
( new Fubar(1,,2))._foo
new命令總是返回一個(gè)對(duì)象,要么是實(shí)例對(duì)象,要么是return語(yǔ)句指定的對(duì)象