javascript – 如何定义`that = this`帮助我创建私有变量/成员?

我正在阅读Douglas Crawford’s piece关于在javascript类中创建私有变量.

在其中他说你必须声明=这是为了“使对象可用于私有方法”.但是,我能够构建一个具有私有成员,私有方法和公共方法的示例,而无需定义= this:

function Form(id_code) {

    //private variable
    var id_code = id_code;
    var color = '#ccc';

    //private method
    function build_style_attribute() {
        return 'style="background-color:'+color+'"';
    }

    //public method
    this.render = function() {
        return '<div '+build_style_attribute()+'>'+id_code+'</div>';
    }
}

var formModules = new Form('modules');

$('p#test').html(formModules.render());

什么指定=这允许我做这个例子还没有做?

添加:

谢谢@Gaby,所以这就是我理解的方式:正如上面的例子所示,我可以访问私有变量而不使用that = this,但它确实让我可以访问公共变量,如下所示:

function Form(id_code) {
    that = this;

    //private variable
    var id_code = id_code;
    var color = '#ccc';

    //public variable
    this.weight = 'bold';

    //private method
    function build_style_attribute() {
        //this will not work with either "weight" or "this.weight"
        return 'style="background-color:'+color+'; font-weight:'+that.weight+'"';
    }

    //public method
    this.render = function() {
        return '<div '+build_style_attribute()+'>'+id_code+'</div>';
    }
}

var formModules = new Form('modules');

$('p#test').html(formModules.render());
最佳答案

By convention, we make a private that
variable. This is used to make the
object available to the private
methods
.

This is a workaround for an
error in the ECMAScript Language
Specification which causes this to be
set incorrectly for inner functions
.

function Test() {
    var that = this;

    function wrongprivate(){
     return this;
    }

    function rightprivate(){
     return that;
    }    

    this.check= function (){
     console.log( wrongprivate() );
     console.log( rightprivate() );
    }

}

var test= new Test();
test.check();
// will output 
// window
// object{}

住在http://www.jsfiddle.net/BpmQ3/1/

转载注明原文:javascript – 如何定义`that = this`帮助我创建私有变量/成员? - 代码日志