-1

I know that 'this' in the Global context refer to the Global object.

Here, I am adding a property called value to the global object and then printing it to the console.

this.value = 34;
console.log(this.value); //34

console.log(value); //Gives compile error 'value is not defined'

According to my understanding, In a function which is not declared inside an object, 'this' refer to the global object.

So, this code should do the exact same thing as above. Add the property called 'value' to the global object.

function b(){
    this.value = 34;
}

b();

However, this is the output.

console.log(this.value); //undefined

console.log(value);     //34

this.value prints undefined.

What is the reason for this difference?

EDIT

I edited the title to show the specific problem I am having. I couldn't find the answer to my problem in the questions linked as duplicates.

Enzio
  • 707
  • 10
  • 23

1 Answers1

0

I think this is a scope issue. Just as if you declare a variable in a function, you cannot access it below that execution context, since you added that variable to the window object in a function, you could not console log it back in the global execution context.

Bezlonir
  • 46
  • 5