问题
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