Scope of Literal Objects - JavaScript

1

I was doing some tests here, and I noticed a difference in this within literal objects:

obj = {
    context: this,
    showContext: function(){ return this }
}

If I do pessoa.context the this will point to the object window , but if I do pessoa.showContext() the this returned will point to the object obj and not to the showContext . Does anyone know the reason for this behavior?

    
asked by anonymous 21.05.2018 / 14:17

2 answers

0

When you declare the object, the value that is assigned to .context is this which is the execution context of that code, or probably window .

I mean, the same thing you do:

var foo = this;
obj = {
    context: foo,

When you run the function it is part of the object and by definition (without being strict mode ) the this returns the object that is the function's parent as the execution context.

So even though you use this in both, they are quite different. The first one is interpreted immediately at the time of assigning the value of .context (that is, when the object is created), the second is called / evaluated at the time the function is executed.

    
21.05.2018 / 14:28
0

This happens because obj was declared inside window , ie:

obj = {};

is the same as

window.obj = {};

However, your showContext has been marked with a function statement, so it gains the scope from where it was created - in this case: obj (which is in scope scope)

    
21.05.2018 / 14:25