1
好吧,我在另一個函數中創建了一個閉包內的構造函數對象(爲了隱藏它與其他可能衝突的腳本)(這將在一瞬間變得清晰)。有沒有辦法給調用函數的引用添加到在封閉的構造函數:添加調用者的引用到in-closure構造函數
// this can be located anywhere within a script
(function() {
function SomeConstructor(param) { this.param = param; }
SomeConstructor.prototype.doSomething = function(a) { this.param = a; return this; }
SomeConstructor.prototype.getParam = function() { return this.param }
// SomeConstructor.prototype.someFunct = ???
return function someFunct(param) {
if (param instanceof SomeConstructor) {
return param;
}
else if (param) {
return new SomeConstructor(param);
}
}
}());
我需要參考的原因,所以我可以someFunct之間的鏈條,它的構造的對象:
someFunct("A").doSomething("a").someFunct("B").doSomething("a").getParam();
請注意我需要保留instanceof
檢查,從而規定了以下功能:
// 1: The inner call creates a new instance of SomeConstructor
// 2: The 2nd(wrapping) call returns the inner calls instance
// instead of creating a new isntance
var a = someFunct(someFunct("b"));
在'SomeConstructor.prototype.someFunct'將'如果(PARAM的instanceof SomeConstructor){...}'繼續處理,因爲它應該。我不得不改變代碼,因爲這不起作用B/C構造函數被重新創建每次someFunct被調用這是這個問題的起源。 – SReject
你的意思是'這個SomeConstructor'實例嗎? – cyon
沒有。 'someFunct(new someFunct(「a」))',第一個調用應該創建一個'SomeConstructor'的新實例,並且包裝調用會'if(param instanceof SomeConstructor){...}'評估爲true在'someFunct'函數內部 – SReject