-1

When I execute this code

f= function(){
  let test= "hello";
  let ret={
     "test": "world",
     "func": function(){
          console.log(test);
         }
    }
  return ret;
 }

let check= f();

check.func()

I get output as "hello". But I am not able to figure out why it is happening. According to what I have read, the scope chain get stacked over each other during definition and last block of scope is attached on runtime on top of them. So shouldn't the scope chain be like- global -> function f -> ret Object -> function test ? Why are the members of ret object excluded from scope chain ? Is it something like members of object are not attached to scope and are just part of context ?

Krrish Raj
  • 1,505
  • 12
  • 28

2 Answers2

0

console.log(this.test) or console.log(ret.test) should give output as "world".

As @deceze said, you have to understand the difference between this.test and test.

this.test is object's property and test is some variable, not an object's property.

Rahul Jain
  • 357
  • 2
  • 17
0

The question was too dumb and there are answers already, but still I want to explain what I was doing wrong, to be helpful to beginners like me.
Actually the article I was reading was treating the terms context and scope in the same fashion. And I was trying to attach object members on scope stack, that does not happen. Fundamentally, scope is function based and context is object based. Every invocation have both scope and context, but they are not same. So, this.test will give "world" as the context is set to ret object and ret.test gives "world" because javascript resolves circular dependency itself.
Moral of the story- scope and context are not same. Don't use it interchangeably.
This post is useful if someone got confused like me.

Community
  • 1
  • 1
Krrish Raj
  • 1,505
  • 12
  • 28