第一種方式:
為了保證構(gòu)造函數(shù)必須與new命令一起使用,一個解決辦法是,在構(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)沒有使用,則直接返回一個實例對象。
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命令總是返回一個對象,要么是實例對象,要么是return語句指定的對象