2013-06-12 61 views
2

new`運營商創建實例我想有和沒有new運營商像創建Point的一個實例:沒有`帶有可變參數列表

Point(5, 10); // returns { x: 5, y: 10 } 
// or 
new Point(5, 10); // also returns { x: 5, y: 10 } 

我得到了它迄今爲止with the help of StackOverflow工作。

function Point() { 
    if (!(this instanceof Point)) { 
    var args = Array.prototype.slice.call(arguments); 
    // bring in the context, needed for apply 
    args.unshift(null); 
    return new (Point.bind.apply(Point, args)); 
    } 
    // determine X and Y values 
    var pos = XY(Array.prototype.slice.call(arguments)); 
    this.x = pos.x; 
    this.y = pos.y; 
} 

但是這看起來太可怕了,我甚至unshifting null入陣,所以我可以用apply。那只是感覺不對。

我發現很多解決方案如何用新的構造函數和構造函數包裝來實現它,但我想盡可能簡單地實現它(這只是一個普通的簡單Point)。

有沒有更簡單的方法來實現這種行爲?

+0

這是必須爲所有功能或只是1?如果只有1,坦率地說,重寫該函數會更好。 –

+0

@ Qantas94Heavy這只是我想表現得像這樣的'Point'功能。但當然它被稱爲多次。 –

回答

2

如果你不介意使用ECMAScript 5個功能,Object.create()可以幫助:

function Point() 
{ var args = Array.prototype.slice.call(arguments); 
    if (this instanceof Point) return Point.apply(null, args); 
    var pos = XY(args); 
    var result = Object.create(Point.prototype); 
    result.x = pos.x; 
    result.y = pos.y; 
    return result; 
} 

如果你需要的ECMAScript 3的兼容性,這個瘋狂的,複雜的解決方案又是另一個(注意,它只是一個包裝new Point的內部等價物):

function Point() 
{ var pos = XY(Array.prototype.slice.call(arguments)); 
    function internalPoint() 
    { this.x = pos.x; 
     this.y = pos.y; 
    } 
    internalPoint.prototype = Point.prototype; 
    return new internalPoint; 
} 
+0

就是這樣。謝謝!好的解決方案 –

+0

呃!我想我正在使用ECMAScript5。 –

+1

@DanLee:請注意,第一種方法將不被IE8和以下版本支持,除非您爲Object.create()添加墊片。話雖如此,我同意第二個是瘋狂的,但不如你所做的那麼瘋狂:O。 –