user669677
user669677

Reputation:

How to access 'this' variable in a prototype function if it is overridden?

If I call set function in my constructor this way, the this variable will be overridden, (like I would use this.set.bind(object,index,element) somehow)

$.each($.parseJSON($selector.val()),this.set);

Set is a prototype function:

Class.prototype.set = function(item,val){
    //here I would like to get the real this in order to set data
    this.data[item] = val;
}

Is there any way to do this?

I have managed it work this way, but I would like to know if any trick exists or not for the first one.

var o = $.parseJSON($selector.val();
for(var i in o)
   this.set(i,o[i]); //this works

UPDETE: These also works:

$.each($.parseJSON($selector.val()),(function(i,e){this.set(i,e);}).bind(this));

or

var self = this;
$.each($.parseJSON($selector.val()),function(i,e){self.set(i,e);});

Upvotes: 1

Views: 55

Answers (1)

Thomas Urban
Thomas Urban

Reputation: 5061

this might be overriden by using Function.call() or Function.apply().

To keep original, you need Function.bind() either natively or by using some polyfill.

Try this:

$.each($.parseJSON($selector.val()),this.set.bind(this));

UPDATE: What about this approach?

var that = this;
$.each($.parseJSON($selector.val()), function() { return that.set.apply( that, arguments ); } );

The typical bind() works similar to this:

function myBind(func,ctx) {
    return function() {
        return func.apply(ctx,arguments);
    };
}

This might be used to simplify second example above, again:

$.each($.parseJSON($selector.val()),myBind(this.set, this));

Upvotes: 1

Related Questions