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

前端 未结 3 1142
情深已故
情深已故 2021-01-06 10:15

If I have the following code:

var obj = {

    x: 34,

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

};

Both al

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 10:44

    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.

提交回复
热议问题