Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better design in order to refer to the own object's properties from an object's method

Tags:

javascript

oop

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?

like image 248
de3 Avatar asked Nov 04 '22 20:11

de3


1 Answers

If you want to make sure that this refers to myObject when you call switchDiv, my recommendation is to change your init function a bit. I've also updated your switchDiv function to reflect this. You still need to reassign this, but only in the init function

var myObject= {
        init: function(config){
            var _this = this;
            this.config=config;
            this.config.InputRadio.on('change',function(){
                _this.switchDiv(); // now "this" will refer to myObject, not the input
            });
        },
        switchDiv: function(){
            if (this.config.InputRadio.filter(":checked").val() === '1'){
                this.config.divYes.hide();
                this.config.divNo.show();
            }else{
                this.config.divYes.show();
                this.config.divNo.hide();
            }
        }
};

By wrapping your call to switchDiv within an anonymous function, you can better maintain the context of this.

Here's a demo showing it in action:

http://jsfiddle.net/VSdAL/

On a related note, it is not recommended to use self when assigning this to a variable for use within callbacks or other functions. self, by default, is a shortcut for window.self, which is a global variable referring to the current window. You don't want to reassign it on the chance that you muck up some other code using self

like image 155
jackwanders Avatar answered Nov 11 '22 18:11

jackwanders