Scope of Literal Objects - Javascript

Asked

Viewed 53 times

1

I was doing some tests here, and I noticed a difference in the 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 for the function showContext. Does anyone know the reason for this behavior?

2 answers

0

this happens because obj was declared within window, that is to say:

obj = {};

is the same as

window.obj = {};

however, your showContext was delcarado with a statement Function, then he wins the Scope from where it was created - in this case: obj (which in turn is in window Scope)

0


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

Which means 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 (other than in strict mode) the this returns the function’s parent object as the execution context.

So even though you use this in both of them are quite different. The first is interpreted immediately at the time of assignment of the value of .context (ie when the object is created), the second is called/evaluated at the time of execution of the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.