本文介绍了为什么`this`在代码示例中没有指向js全局作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么this
在下面的代码中没有指向js全局作用域?
Why this
is not point to js global scope in the code below ?
<html>
<head></head>
<body>
<script type="text/javascript">
var valueHolder = {
value: '',
setValue: function(newValue) {
this.value = newValue;
},
getValue: function() {
return this.value;
}
}
valueHolder.setValue("hello world");
alert(valueHolder.getValue()); // return "hello world"
alert(valueHolder.value); // return "hello world"
alert(window.value); // return "undefined"
</script>
</body>
</html>
推荐答案
取决于对函数的引用(cf 11.2.3 of 规范):
Depends on the reference to the function (c.f. 11.2.3 of the spec):
var valueHolder = {
value: '',
setValue: function(newValue) {
this.value = newValue;
},
getValue: function() {
return this.value;
}
}
var set = valueHolder.setValue,
get = valueHolder.getValue;
set('test');
alert(get()); // return "test"
alert(valueHolder.value); // return ""
alert(window.value); // return "test"
当在上下文中引用时 this
设置为相关上下文(在您的示例中为 valueHolder
).在我上面的例子中,函数定义显然是相同的,但是函数引用不在任何对象的上下文中,在这种情况下 this
被设置为全局上下文 (window
代码>).
When referred to in context this
is set to the relevant context (valueHolder
in your example). In my example above, the function definitions are clearly identical, but the function references are not in the context of any object, and in that case this
is set to the global context (window
).
这篇关于为什么`this`在代码示例中没有指向js全局作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!