在 JavaScript 中,若直接呼叫建構函數而不加 new,例如 RectF(10,10,10,10),函數內部的 this 不會指向新建立的物件,導致屬性沒有正確設定,傳入其他函數的參數可能是 undefined。
function RectF(x, y, w, h) {
this.X = x;
this.Y = y;
this.Width = w;
this.Height = h;
}
function PointF(x, y) {
this.X = x;
this.Y = y;
}
// 正確:必須使用 new
var rect = new RectF(10, 10, 10, 10);
var point = new PointF(2, 19);
var ret = isin(rect, point);
RectF() 時,this 代表全域物件(瀏覽器中為 window),屬性會被綁到全域,而函數沒有回傳值,因此變數會是 undefined。new RectF() 時,JavaScript 會建立新物件,並將 this 綁定到該物件,同時自動回傳這個物件。return this,即使不加 new 也能回傳目前的 this,但這不是慣例,且記憶體配置與物件建立機制仍有差異。