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?
Add开发者_StackOverflowed:
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());
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{}
Live at http://www.jsfiddle.net/BpmQ3/1/
Without using 'that' You can also achieve rightThis:
function someFunction(){
var that = this;
function getThis(){
return this;
};
function getThat(){
return that;
};
return{
getThis:getThis,
getThat:getThat
}
}
var a = new someFunction();
alert(a.getThis()); // Object
alert(a.getThat()); // Object
精彩评论