Search code examples
javascriptjavascript-objectsobject-literal

Javascript Literal Object Notation This vs Object Name


I have an object literal like this:

var test = {
    one: function() {
    },
    two: function() {
        this.one(); // call 1
        test.one(); // call 2
    }
};

What is the difference between the calls in the two function (using the object literal name versus using this)?


Solution

  • test is always bound within the closure of the two function to the variable test whereas this depends on how the function is called. If the function is called using the regular object member access syntax, this becomes the object owning the function:

    test.two(); // inside, "this" refers to the object "test"
    

    You can change the value of this by using Function.prototype.call:

    test.two.call(bar); // inside, "this" refers to the object "bar"
    

    But the value of test remains the same inside the two function, regardless of how the function is invoked.