I have a ‘yesno’ input radio. When user clicks yes, a yesDiv is shown, and when user clicks no, noDiv is shown.
In order to implement that I created the object myObject.
var myObject= {
init: function(config){
this.config=config;
this.config.InputRadio.bind('click',this.config,this.switchDiv);
},
switchDiv: function(ev){
self=ev.data;
if ($(this).val()==1){
self.divYes.hide();
self.divNo.show();
}else{
self.divYes.show();
self.divNo.hide();
}
}
}
myObject.init({
InputRadio:$("input[name=yesno]"),
divYes:$("#yesDiv"),
divNo:$("#noDiv")
});
This works, I know that I can’t use this to refer to the object’s properties inside the method ‘switchDiv’ because of the scope of ‘this’ inside a function. I found the solution of sending this.config as a parameter and then using self=ev.data, in a related question ( Referencing own object properties.)
But now my question is: Isn’t a little strange the fact that whenever I want to access to an object’s own properties from a method of that object, I have to pass them as a parameter in the method? Isn’t there a better way to declare the objects to avoid that?
Unless you need the public API of your object, I think you’re best off just not creating such an object at all. Keep all the state in a hidden scope, as in this fiddle
Or, if you only need the one, then don’t even make the function public:
(but that latter might be done in somewhat simpler ways if you don’t need more than one.)