任何函式皆可作為構造函式,關鍵在於是否使用 new 呼叫。理解 new 運算子的內部步驟、返回值規則、this 綁定,是掌握 JS 物件導向的基石。
__proto__ 指向構造函式的 prototype。this 綁定到該新物件。new Something()),**捨棄 this,直接回傳該物件**。return 或 return;,**回傳 this**。
function Test() {
this.a = 10;
return function() { return 1; }; // 返回函式 (物件)
}
var m = new Test(); // m 是返回的函式,不是 Test 實例
console.log(m); // [Function]
console.log(m.a); // undefined
function Test() {
this.a = 10;
return 1; // 原始值
}
var m = new Test(); // m 是 Test 實例
console.log(m); // Test { a: 10 }
console.log(m.a); // 10
function Test() {
this.a = 10;
return 1;
}
var n = Test(); // 直接呼叫,this 指向 window (非嚴格模式) 或 undefined (嚴格模式)
console.log(n); // 1 (返回值)
console.log(window.a); // 10 (污染全域)
function Test() {
if (!new.target) {
throw new Error('必須使用 new 呼叫');
}
this.a = 10;
}
'use strict' 下,直接呼叫構造函式 this 為 undefined,會拋錯誤,提早發現漏寫 new。class 語法,避免手動管理原型與 new 陷阱。