Skip to content

Instantly share code, notes, and snippets.

@madhums
Forked from cjohansen/gist:4135065
Created November 23, 2012 12:52
Show Gist options
  • Save madhums/4135481 to your computer and use it in GitHub Desktop.
Save madhums/4135481 to your computer and use it in GitHub Desktop.
Naming this in nested functions

tl;dr

If you must nest functions in a way that requires access to multiple this', alias outer this to something meaningful - describe the value it's holding. Treat this as the invisible first argument.

In general though, avoiding the situation (nested functions and frivolous use of this) will frequently produce clearer results.

Naming this in nested functions

I was accidentally included in a discussion on how to best name this in nested functions in JavaScript. +1's were given to this suggestion of using _this.

Giving style advice on naming nested this without a meaningful context isn't too helpful in my opinion. Examples below have been altered to have at least some context, although a completely contrived and stupid one.

Assume this setup:

var morgan = new Person("Morgan");

Bad

morgan.logger = function() {
  var self = this;
  return function() {
    console.log(self);
  };
};

Bad

morgan.logger = function() {
  var that = this;
  return function() {
    console.log(that);
  };
};

Bad (still no good in my opinion)

morgan.logger = function() {
  var _this = this;
  return function() {
    console.log(_this);
  };
};

Meaningful name: Better

morgan.logger = function() {
  var person = this;
  return function() {
    console.log(person);
  };
};

Another more realistic example

Function.prototype.throttle = function (ms) {
    var fn = this;
    var timer;
    return function () {
        clearTimeout(timer);
        var args = [].slice.call(arguments);
        timer = setTimeout(function () {
            fn.apply(this, args);
        }, ms || 100);
    };
};

var throttled = myFunc.throttle(50);
throttled("Hey there!");

In the above example, "fn" is way superior to "_this". Still, the following example would be even better:

function throttle(fn, ms) {
    var timer;
    return function () {
        clearTimeout(timer);
        var args = [].slice.call(arguments);
        timer = setTimeout(function () {
            fn.apply(this, args);
        }, ms || 100);
    };
};

var throttled = throttle(myFunc, 50);
throttled("Hey");
throttled("Hey there!");

In summary

See tl;dr ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment