LongInt
LongInt

Reputation: 1769

Whats the difference between using 'this' and the object name for reference inside the object?

If I have the following code:

var obj = {

    x: 34,

    init: function() {
        alert(this.x);
        alert(obj.x)
    }

};

Both alerts displays 34. But what is the difference, and is one better than the other?

http://jsfiddle.net/4scz435q/

I made a test in jsperf, and it seems this is a bit faster, but I still don't understand the inner workings of the two versions. http://jsperf.com/name-vs-this-in-obj

Upvotes: 5

Views: 247

Answers (3)

Siddharth
Siddharth

Reputation: 1166

Besides the shadowing and so on mentioned in the previous answers, using this is more generic and thus will work more effectively in certain scenarios. Let me illustrate.

var object = {
    name: 'John Doe',
    print: function () {
        console.log(object.name);
    }
};

var anotherObject = Object.create(object);

object.print(); // John Doe
anotherObject.print(); // John Doe

anotherObject.name = 'Jane Doe';
console.log(anotherObject.name); // Jane Doe
anotherObject.print(); // John Doe

What I'm doing here is that I'm creating an object that has a name 'John Doe' and then I create anotherObject that inherits from it. Now in this scenario, you would expect anotherObject.print() to print its own name. But it doesn't.

This is because your function is tied to that particular object. If I would have used this instead, it would have referred to the new object appropriately.

Also, imagine what happens if I were to do this.

delete object.name;
anotherObject.print() // Error!

http://jsfiddle.net/uxy08zxz/

This is because even though you think it has nothing to do with that previous object, its function still refers to that very property. Doesn't it?

Hence, keep it generic. Use this. Keeps your code drier, I say.

Upvotes: 5

Nicky McCurdy
Nicky McCurdy

Reputation: 19554

I would say there are two differences here:

  1. this can get shadowed. Creating an anonymous function in JavaScript can unfortunately replace this with a reference to the new anonymous function you're in, and not the current object you want access to.
  2. When you're not worrying about shadowing, this is more flexible if the name of the object changes.

this is probably faster in this case because JavaScript won't need to look up the reference.

Upvotes: 2

John Sterling
John Sterling

Reputation: 1111

this inside the function is not necessarily the same as obj. It depends on how the function is called.

  • if called using obj.init(), obj will be the same as this.
  • if called using an event handler, or something like setTimeout setTimeout(obj.init, 500), this will be the global object (window in browsers, unless you're using strict mode)

Good MDN reference on all of this

Upvotes: 3

Related Questions