jchamb
jchamb

Reputation: 389

Javascript prototypal inheritance prototype function call

Have a question about calling one prototype function in another prototype function.

for instance lets say I have a basic slider with two prototype functions.

function Slider() {

}

Slider.prototype.transition = function() {

}

Slider.prototype.setTargets = function() {

}

What is the proper way of calling the setTargets function inside of the transition function so something like this:

Slider.prototype.transition = function() {
   this.target.fadeOut('normal', function() {
      // call setTargets?  
      this.setTargets(); // errors when i do this
   });
}

thanks for the help

Upvotes: 1

Views: 127

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47099

If this.target is an jQuery Object the callback of fadeOut will be called with this as the DOMNode.

Do this instead:

Slider.prototype.transition = function() {
   var me = this;
   this.target.fadeOut('normal', function() {
      me.setTargets(); // <-- See me
   });
}

I have chosen the name that me for all my initialized references to this. I never used that me for DomNodes, etc. makes sence for me.

Please see comments for furture views on this point.

EDIT:

Acually i used me not that - Dont know what im thinking ?? !


And for comment:

Slider.prototype.transition = function() {
   var me = this;
   this.target.fadeOut('normal', function() {
      var domThis = this;
      me.setTargets(); // <-- See me
      setTimeout(function() {
          // Use domThis [Dom Node]
      }, 123);
   });
}

Or:

You can make a jQuery object of this:

      var $this = $(this);
      me.setTargets(); // <-- See me
      setTimeout(function() {
          // Use $this [jQuery Object]
      }, 123);

If you need the jQuery Object of this you can refer to: me.target

      me.setTargets(); // <-- See me
      setTimeout(function() {
          // Use me.target [jQuery Object]
      }, 123);

Upvotes: 1

Scott Sauyet
Scott Sauyet

Reputation: 50787

The fadeOut function is not called in the context of your slider object.

Slider.prototype.transition = function() {
    var slider = this;
    this.target.fadeOut('normal', function() {
        // call setTargets?  
        slider.setTargets(); // should work now.
    });
}

Upvotes: 0

Related Questions