一般建立物件時會使用 new,例如 new Person(...)。但在某些內建物件中,即使不加 new,也能得到可用結果。
var reg1 = new RegExp("^he$");
var reg2 = RegExp("^he$");
console.log(reg1.test("he"));
console.log(reg2.test("he"));無論有無 new,RegExp 都會回傳正則表達式物件。
var str1 = new String(1);
var str2 = String(1);
console.log(typeof str1);
console.log(typeof str2);使用 new 時,typeof 會是 object;不使用 new 時,則會回傳原始型別,例如 string、number、boolean。
function Person(name, age) {
this.name = name;
this.age = age;
}
var p = Person("lily", 20);
console.log(p);這時 p 會是 undefined,因為 Person 沒有 new 時不會自動建立物件。若希望不寫 new 也能建立物件,可以在函式內部判斷 this 是否為全域物件,若是則改為遞迴呼叫 new。
因此,是否能省略 new,取決於該建構函式的實作方式,而不是所有函式都通用。