Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is having a reference to this for easy scoping a good or bad idea?

I sometimes assign the this pointer to a var. The benefit of it is that I don't loose the scope in anonymous callback functions. Is that a good or bad idea?

Example:

var Foo = (function($) {
  var Foo = function() {
    var self;

    self = this;

    this.init = function() {
      $('#foo').click(function(e) {
        self.onClick();
      });
    };

    this.onClick = function() {
      console.log(this);
    };

    this.init();
  };

  return function() {
    return new Foo();
  };
})(jQuery);

Thank you!
{Jim}

like image 376
Benny Schudel Avatar asked Dec 15 '25 09:12

Benny Schudel


2 Answers

If you need a reference to the this value of a containing scope (which is certainly a reasonable requirement), it must be a good idea, particularly in cases where you are not in control of the function call (such as event handler functions) where it's your only option.

like image 104
Tim Down Avatar answered Dec 16 '25 22:12

Tim Down


It's not a bad idea. Whether or not it is a good idea is mostly stylistic.

An alternate way to write your code is to hold a reference to the onClick function in the closure. However, this won't be bound for the onClick function when calling it this way. For example:

var Foo = (function($) {
  var Foo = function() {
    this.init = function() {
      $('#foo').click(function(e) {
        onClick();
      });
    };

    var self = this;  // Or use ES5's Function.prototype.bind

    var onClick = this.onClick = function() {
      console.log(self);
    };

    this.init();
  };

  return function() {
    return new Foo();
  };
})(jQuery);

I prefer this style to using self (or that or whatever name you chose) if the object's methods are all in a closure (as in your case).

like image 36
strager Avatar answered Dec 16 '25 23:12

strager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!