在Javascript中确保"此"上下文的最佳做法是什么?

jth*_*mas 9 javascript this

这是一个带有公共和私有方法的简单Javascript类的示例(小提琴:http://jsfiddle.net/gY4mh/).

function Example() {
    function privateFunction() {
       // "this" is window when called.
       console.log(this);
    }

    this.publicFunction = function() {
       privateFunction();
    }
}

ex = new Example;
ex.publicFunction();
Run Code Online (Sandbox Code Playgroud)

从公共部门调用私有函数会导致"this"成为窗口对象.我应该如何确保使用类上下文而不是窗口调用我的私有方法?这会不合适吗?

bas*_*rat 8

使用闭包.基本上,在函数中声明的任何变量仍然可用于该函数内的函数:

var Example = (function() {
    function Example() {
        var self = this; // variable in function Example
        function privateFunction() {                  
            // The variable self is available to this function even after Example returns. 
            console.log(self);
        }

        self.publicFunction = function() {
            privateFunction();
        }
    }

    return Example;
})();

ex = new Example;
ex.publicFunction();
Run Code Online (Sandbox Code Playgroud)