为什么在代码示例中' this '不是指向js全局作用域

Why `this` is not point to js global scope in the code example

本文关键字:js 作用域 全局 this 代码 为什么      更新时间:2023-09-26

为什么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>

取决于对函数的引用(参见规范的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)。

返回undefined,因为value是对象内部的键,在window对象中不可见。您将使用

访问
window.valueHolder.value

(要清楚,在你的代码this关键字是指valueHolder对象)

为什么你认为它会是全局作用域?

当一个对象有一个引用函数的属性时,你可以使用点符号来调用这个函数:

valueHolder.getValue();

然后在函数中JavaScript自动将this设置为对象。