Javascript文字对象表示法this vs Object Name [英] Javascript Literal Object Notation This vs Object Name
问题描述
我有一个这样的对象文字:
I have an object literal like this:
var test = {
one: function() {
},
two: function() {
this.one(); // call 1
test.one(); // call 2
}
};
two
函数中的调用(使用对象文字名称与使用this
)之间的区别是什么?
What is the difference between the calls in the two
function (using the object literal name versus using this
)?
推荐答案
test
始终在two
函数的闭包内绑定到变量test
,而this
取决于函数的调用方式.如果使用常规对象成员访问语法调用该函数,则this
成为拥有该函数的对象:
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"
您可以使用Function.prototype.call
更改this
的值:
test.two.call(bar); // inside, "this" refers to the object "bar"
但是test
的值在two
函数内部保持不变,无论该函数如何调用.
But the value of test
remains the same inside the two
function, regardless of how the function is invoked.
这篇关于Javascript文字对象表示法this vs Object Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!