Я читал статью Дугласа Кроуфорда о создании закрытых переменных в классах javascript.
В ней он говорит, что вы должны указать that = this
, чтобы "сделать объект доступным для частногометоды».Тем не менее, я смог создать пример, который имеет закрытые члены, приватные методы и открытые методы без определения that = 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());
Что бы указав that = this
, я позволил бы сделать этот примерне делает?
Добавлено:
Спасибо @Gaby, вот как я это понимаю: как показывает приведенный выше пример, у меня есть доступ к private переменные без использования 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());