2

例:

function testFunc() {
  this.insideFunc = function(msg) {
    alert(msg);
  }
  return this;
}

testFunc().insideFunc("Hi!");
insideFunc("Hi again!");

内部関数がグローバルスコープで表示されるのはなぜですか、それを防ぐ方法は?

4

3 に答える 3

5

それはですからthisですwindow

この方法で使用するには、次を使用thisする必要があります。

var _testFunc = new testFunc();
于 2012-09-17T18:30:10.213 に答える
2

ethagnawlの答えに基づいてnew、呼び出し元が次のことを忘れた場合に、このトリックを使用して関数を強制的に実行できます。

function testFunc() {
    // if the caller forgot their new keyword, do it for them
    if (!(this instanceof testFunc)) {
        return new testFunc();
    }

    this.insideFunc = function(msg) {
        alert(msg);
    }
    return this;
}

http://jsfiddle.net/qd7cW/

于 2012-09-17T18:36:10.640 に答える
2

あなたはこのようなことを試すことができます:

var testFunc = function() {
    function insideFunc(message) {
        alert(message);
    }
    return {
        insideFunc: insideFunc
    }
}
testFunc().insideFunc("Hi!");
insideFunc("Hi again!");
于 2012-09-17T18:37:02.483 に答える