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

2019-09-02 05:51发布

问题:

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.