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

限于喜欢 提交于 2019-12-12 04:59:41

问题


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>

回答1:


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"

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).




回答2:


it returns undefined because value is a key inside an object and is not visible inside the window object. you will access using

window.valueHolder.value

(to be clear, in your code this keyword is referring to valueHolder object)




回答3:


Why do you think it would be the global scope?

When an object has a property that references a function and you call that function using dot notation like this:

valueHolder.getValue();

Then within the function JavaScript automatically sets this to be the object.



来源:https://stackoverflow.com/questions/8656774/why-this-is-not-point-to-js-global-scope-in-the-code-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!