Javascript Literal Object Notation This vs Object Name

社会主义新天地 提交于 2019-12-13 15:56:17

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/9092201/javascript-literal-object-notation-this-vs-object-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!