0

私は正式に、JavaScript で変数を代入しようとして 1 日を費やしました! この同じ質問を 4 つの異なる方法で質問して申し訳ありませんが、これが私が今朝始めたものであり、これでうまくいきます。ここで、2 つ目のメソッドを追加する必要があります。

Application = {};
(function() {
    var closure = {};

    Application.myFirstMethod = function() {
        if (arguments.length) {
            closure = arguments[0];
        } else {
            return closure;
        }
    }
})();

Application.myFirstMethod(3.14);
result = Application.myFirstMethod();
log(result);

私の質問は次のとおりです: に追加mySecondMethodする場合、現在クロージャーと呼ばれている変数を使用せずApplicationに の値を保持するにはどうすればよいですか?arguments[0]

4

3 に答える 3

1

プロトタイプ指向プログラミング言語という用語の意味で、オブジェクトにプロパティを追加することを探しているようです。現在の呼び出しコンテキストを表し、メソッドを呼び出すときに Application オブジェクトに設定される「this」オブジェクトを使用するだけです。

Application = {};
(function() {

  Application.myFirstMethod = function() {
    if (arguments.length) {
        this.foo = arguments[0];
    } else {
        return this.foo;
    }
  };
  Application.mySecondMethod = function() {
    if (arguments.length) {
        this.bar = arguments[0];
    } else {
        return this.bar;
    }
  };
})();

Application.myFirstMethod(3.14);
console.log(Application.myFirstMethod());

Application.mySecondMethod(2097);
console.log(Application.mySecondMethod());
console.log(Application.myFirstMethod());
于 2013-10-09T20:38:54.063 に答える
0

これが私が理解したものです。newでも、どこかでその言葉を使う必要があるかもしれません。

Application = {};
(function() {
    Application.myFirstMethod = FirstMethod();
    Application.mySecondMethod = SecondMethod();

    function FirstMethod() {
        var closure = {};
        return function(myArgument) {
            if (arguments.length) {
                closure.result = arguments[0]; // myArgument
            } else {
                return closure.result;
            }
        }
    }
    function SecondMethod() {
        var closure = {};
        return function(myArgument) {
            if (arguments.length) {
                closure.result = arguments[0]; // myArgument
            } else {
                return closure.result;
            }
        }
    }
})();


Application.myFirstMethod(3.14);
result = Application.myFirstMethod();
log(result);

Application.mySecondMethod(2013);
result = Application.mySecondMethod();
log(result);
于 2013-10-09T20:54:05.127 に答える