0

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>
nahab
  • 1,168
  • 15
  • 35

3 Answers3

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)

Fabrizio Calderan loves trees
  • 109,094
  • 24
  • 154
  • 160
  • -1 because question is "Why [this] is not point to js global scope in the code below" or in other words "Why [this] keyword is referring to valueHolder object" – nahab Dec 28 '11 at 15:07
2

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

davin
  • 41,227
  • 7
  • 73
  • 77
0

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.

nnnnnn
  • 138,378
  • 23
  • 180
  • 229