2

例子:

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

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

为什么内部函数在全局范围内可见,如何防止?

4

3 回答 3

5

那是因为thiswindow

this以这种方式使用,您必须使用:

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

你可以尝试这样的事情:

var testFunc = function() {
    function insideFunc(message) {
        alert(message);
    }
    return {
        insideFunc: insideFunc
    }
}
testFunc().insideFunc("Hi!");
insideFunc("Hi again!");
于 2012-09-17T18:37:02.483 回答
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 回答