Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a best practice for ensuring "this" context in Javascript?

Here's a sample of a simple Javascript class with a public and private method (fiddle: http://jsfiddle.net/gY4mh/).

function Example() {
    function privateFunction() {
       // "this" is window when called.
       console.log(this);
    }

    this.publicFunction = function() {
       privateFunction();
    }
}

ex = new Example;
ex.publicFunction();

Calling the private function from the public one results in "this" being the window object. How should I ensure my private methods are called with the class context and not window? Would this be undesirable?

like image 438
jthomas Avatar asked Apr 26 '13 00:04

jthomas


3 Answers

Using closure. Basically any variable declared in function, remains available to functions inside that function :

var Example = (function() {
    function Example() {
        var self = this; // variable in function Example
        function privateFunction() {                  
            // The variable self is available to this function even after Example returns. 
            console.log(self);
        }

        self.publicFunction = function() {
            privateFunction();
        }
    }

    return Example;
})();

ex = new Example;
ex.publicFunction();
like image 154
basarat Avatar answered Sep 25 '22 01:09

basarat


Another approach is to use "apply" to explicitly set what the methods "this" should be bound to.

function Test() {
    this.name = 'test';
    this.logName = function() {
        console.log(this.name);
    }
}

var foo = {name: 'foo'};

var test = new Test();
test.logName()
// => test
test.logName.apply(foo, null);
// => foo

Yet another approach is to use "call":

function Test() {
    this.name = 'test';
    this.logName = function() {
        console.log(this.name);
    }
}

var foo = {name: 'foo'};

var test = new Test();
test.logName()
// => test
test.logName.call(foo, null);
// => foo

both "apply" and "call" take the object that you want to bind "this" to as the first argument and an array of arguments to pass in to the method you are calling as the second arg.

like image 41
nicksweet Avatar answered Sep 26 '22 01:09

nicksweet


It is worth understanding how the value of this in javascript is determined in addition to just having someone tell you a code fix. In javascript, this is determined the following ways:

  1. If you call a function via an object property as in object.method(), then this will be set to the object inside the method.

  2. If you call a function directly without any object reference such as function(), then this will be set to either the global object (window in a browser) or in strict mode, it will be set to undefined.

  3. If you create a new object with the new operator, then the constructor function for that object will be called with the value of this set to the newly created object instance. You can think of this as the same as item 1 above, the object is created and then the constructor method on it is called.

  4. If you call a function with .call() or .apply() as in function.call(xxx), then you can determine exactly what this is set to by what argument you pass to .call() or .apply(). You can read more about .call() here and .apply() here on MDN.

  5. If you use function.bind(xxx) this creates a small stub function that makes sure your function is called with the desired value of this. Internally, this likely just uses .apply(), but it's a shortcut for when you want a single callback function that will have the right value of this when it's called (when you aren't the direct caller of the function).

  6. In a callback function, the caller of the callback function is responsible for determining the desired value of this. For example, in an event handler callback function, the browser generally sets this to be the DOM object that is handling the event.

There's a nice summary of these various methods here on MDN.

So, in your case, you are making a normal function call when you call privateFunction(). So, as expected the value of this is set as in option 2 above.

If you want to explictly set it to the current value of this in your method, then you can do so like this:

var Example = (function() {
    function Example() {
        function privateFunction() {
            // "this" is window when called.
            console.log(this);
        }

        this.publicFunction = function() {
            privateFunction.call(this);
        }
    }

    return Example;
})();

ex = new Example;
ex.publicFunction();

Other methods such as using a closure and defined var that = this are best used for the case of callback functions when you are not the caller of the function and thus can't use 1-4. There is no reason to do it that way in your particular case. I would say that using .call() is a better practice. Then, your function can actually use this and can behave like a private method which appears to be the behavior you seek.

like image 34
jfriend00 Avatar answered Sep 24 '22 01:09

jfriend00