为什么下面代码中的this
没有指向js全局作用域?
<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>
最佳答案
取决于对函数的引用(参见 the spec 的 11.2.3):
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
).
关于javascript - 为什么代码示例中 `this`没有指向js全局作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8656774/