Ben_hawk
Ben_hawk

Reputation: 2486

JavaScript change ownership of this

I have an object, something like so

var Egg = function(){

   this.test = $(.slider .label);

    $('.slider').slider({
       min: 1,
       value: 2,
       step: 1,
       value: 10,
       slide: function(){
         this.test.html(ui.value)
       }
    });

}

I want to use my variable test inside the slider object. However in its current form this refers to the slider and not my egg object, and so trying to use this.test when the slider moves results in undefined.

How can I make this refer to my object and not the slider.

Thanks

Upvotes: 0

Views: 103

Answers (2)

user1106925
user1106925

Reputation:

This is jQuery? Use $.proxy...

$('.slider').slider({
   min: 1,
   value: 2,
   step: 1,
   value: 10,
   slide: $.proxy(function(){
     this.test.html(ui.value)
   }, this)
});

Without jQuery, you could use Function.prototype.bind...

$('.slider').slider({
   min: 1,
   value: 2,
   step: 1,
   value: 10,
   slide: function(){
     this.test.html(ui.value)
   }.bind(this)
});

Upvotes: 1

hackattack
hackattack

Reputation: 1087

this has dynamic scope, so inside the slide function this is referring to whatever object called that function. this is not equal to what it was equal to when the function is defined (i dont know if im saying that very clearly ... read this http://hoolihan.net/blog-tim/2009/02/17/static-vs-dynamic-scope/). However, you can save this in another variable and access it that way

var Egg = function(){

   var self = this;

   this.test = $(.slider .label);

    $('.slider').slider({
       min: 1,
       value: 2,
       step: 1,
       value: 10,
       slide: function(){
         self.test.html(ui.value)
       }
    });

}

Upvotes: 2

Related Questions