1

わかりました。別の関数のクロージャー内にコンストラクターオブジェクトを作成しています(競合する可能性のある他のスクリプトからオブジェクトを非表示にするため)(これはすぐに明らかになります)。呼び出し元関数の参照を閉じたコンストラクターに追加する方法はありますか?

// 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"));
4

1 に答える 1

1

最初にプロトタイプのプロパティに関数を割り当ててから、次のプロパティを返します。

(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 = function someFunct(param) {
     if (param) {
          return new SomeConstructor(param);
     }
   }

   return SomeConstructor.prototype.someFunct; 
 }());
于 2012-11-16T09:58:22.060 に答える