To evaluate name(a, 'ddd')
, the compiler will create a new stack frame and place two slots on it, one a
, which will be a reference to the global object of the same name, and str2
, which will contain the string literal 'ddd'
. Then the body will be evaluated.
In the body, to evaluate a.display(function(){...})
, the value of a.display
will be resolved to the function with parameter n
. To evaluate n(function(){...})
, a new stack frame will be created with n
assigned to the closure that results from evaluating the anonymous callback (a closure being a combination of a pointer to the static scope of the function and the compiler generated code for the function itself). Then the body of the a.display
function will be evaluated.
In the body, the console.log
will be called with the given string. Then the callback n()
will be evaluated. Since n
doesn't take any parameters, it will just be evaluated in the topmost stack frame, so when the time comes to evaluate console.log(str2)
, str
will not be found on the current stack frame, so the compiler will follow the scope chain all the way to the frame where we bound 'ddd'
to str
and a
to the function.
That's a pretty long answer to your simple question. I'll try to shorten it later. Also, corrections are welcome, as I'm being very hand-wavy with the evaluation process.