I was reading Douglas Crawford’s piece on creating private variables in javascript classes.
In it he says you have to state that = this in order to “make the object available to private methods”. However, I was able to build an example which has private members, private methods and public methods without defining 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());
What would specifying that = this allow me to do which this example does not already do?
Added:
Thanks @Gaby, so this is how I understand it: as the above example shows, I have access to private variables without using that=this but it does give me access to public variables as shown here:
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());
Live at http://www.jsfiddle.net/BpmQ3/1/