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

前端 未结 3 1145
情深已故
情深已故 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

    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

提交回复
热议问题