在javascript中使用'this'中的相同对象的键值对 [英] using key value pair of same object inside itself with 'this' in javascript
问题描述
假设我有两个对象,例如
Let's say I have two objects like
var a = {
b: 1,
c: this.b
};
和
var funcObj = {
b : function() {
return 1;
},
c: function() {
console.log(return this.b())
}
}
在记录这两个时,如
console.log(a.c)//results undefined
console.log(funcObj.c()) //results 1
为什么第一个函数不能使用this属性但第二个函数可以使用?
我真的很困惑。
Why can't the first function use the this property but the second one can? I am really confused.
推荐答案
答案取决于这个
指的是每个上下文。在JavaScript中,此
绑定到调用当前函数时点(。)左侧的任何对象。如果我们不在函数中,事情就会变得有点毛茸茸 - 这个
是全局窗口
对象或者 undefined
,具体取决于环境。
The answer depends on what this
refers to in each context. In JavaScript, this
is bound to whatever object was on the left of the dot (.) when the current function was called. If we're not in a function, things get a little hairier -- this
is either the global window
object or undefined
, depending on the environment.
在您的第一个示例中,的值为此
取决于周围的上下文。当JavaScript构建您的对象 a
时,它会计算 this.b
。无论什么对象这个
目前被绑定没有 b
属性,所以 c
属性设置为未定义
。
In your first example, the value of this
is dependent on the surrounding context. As JavaScript builds your object a
, it evaluates this.b
. Whatever object this
is currently bound to has no b
property, so the c
property is set to undefined
.
在第二个示例中,当您调用<$ c $时c> funcObj.c()函数中的此
绑定到 funcObj
。因此,当您要求 b
属性时,您将获得上面定义的 b
。 funcObj.b
这个函数实际上是无关紧要的。以下也适用:
In your second example, when you call funcObj.c()
the this
in the function gets bound to funcObj
. So, when you ask for the b
property, you get the b
you defined above. The fact that funcObj.b
is a function is actually irrelevant. The following would work just as well:
var funcObj = {
b : 1,
c: function() {
console.log(return this.b)
}
}
这篇关于在javascript中使用'this'中的相同对象的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!