Harper
Harper

Reputation: 1305

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)?

Upvotes: 2

Views: 659

Answers (2)

Ateş Göral
Ateş Göral

Reputation: 140042

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.

Upvotes: 5

Stefan
Stefan

Reputation: 4206

The difference is that the second call will always be bound to the test object, whereas this might be rebound to some other object:

var other = {
    one: function () {
        alert('other.one');
    }
};

// call test.two as a method of object other
test.two.call(other); // calls other.one and test.one

Upvotes: 1

Related Questions