2

I want to set value of "text" property to "value" property.

Example.html:

<script>
    var obj = {
        text: "Hello",
        value: this.text
        /*
        value: function() {
            return this.text;
        }
        */
    };

    console.log(obj.text); // Output: Hello
    console.log(obj.value); // Output: undefined

    // console.log(obj.value()); // Output: Hello
</script>

Why?

2 Answers2

0

the this keyword in javascript means the context which called the current action. so if you want to achieve your issue do the following:

  var obj = {
    text: "Hello"
  };

  obj.value = obj.text;

https://jsfiddle.net/2zzdnmeb/

in your case this would be the window object - but still: why do you want to do this? you already have your value

messerbill
  • 5,499
  • 1
  • 27
  • 38
0

bcoz this refers to global object in your code. this is available inside functions otherwise it will refer to the global object (current execution context)

  var obj = {
        text: "Hello",
        value: this
    };

    console.log(obj.text);  // Hello
    console.log(obj.value);  // window

but in this case

 var obj = {
        text: "Hello",
       value: function() {
            return this.text;
        }
    };

    console.log(obj.text);  // Hello
    console.log(obj.value()); //Hello

now this in value() refers to your object

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24