What is the difference between using 'this' and the object name to reference within the object?

If I have the following code:

var obj = {

    x: 34,

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

};

      

Both warnings display 34. But what's the difference and one is better than the other?

http://jsfiddle.net/4scz435q/

I did a test in jsperf and it seems a this

little faster, but I still don't understand the inner workings of the two versions. http://jsperf.com/name-vs-this-in-obj

+3


source to share


3 answers


Apart from the shading, etc. mentioned in the previous answers, the usage this

is more general and thus will work more efficiently 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 am doing here is that I create object

which is named "John Doe" and then I create anotherObject

which inherits from it. Now in this case, you expect to anotherObject.print()

print its own name. But this is not the case.

This is because your function is bound to that specific object. If I were to use it this

instead, it would reference the new object appropriately.

Also imagine what would happen if I did this.



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

      

http://jsfiddle.net/uxy08zxz/

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

Hence, keep it general. Use this

. I say keeps your code dry.

+4


source


this

inside a 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 with an event handler, or something like the setTimeout setTimeout(obj.init, 500)

    , this

    it is a global object ( window

    in the browser, if you are not using strict mode)


Good MDN link to all of this

+2


source


I would say that there are two differences here:

  • this

    may be shaded. Creating an anonymous function in JavaScript can, unfortunately, replace it with a this

    reference to the new anonymous function you are in, rather than the current object you want to access.
  • If you are not worried about shading, it this

    is more flexible if the object name changes.

this

is probably faster in this case because JavaScript doesn't need to search for a link.

+1


source







All Articles