Skip to content

Instantly share code, notes, and snippets.

@Constellation
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save Constellation/beaba9472f0fe878cefb to your computer and use it in GitHub Desktop.

Select an option

Save Constellation/beaba9472f0fe878cefb to your computer and use it in GitHub Desktop.

http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist

  1. In [[Call]], we call the PrepareForOrdinaryCall to setup the callee environment
  2. In PrepareForOrdinaryCall, we create the FunctionEnvironment by calling NewFunctionEnvironment and use it as the callee's environment
  3. After that, we enter OrdinaryCallEvaluateBody, and it calls FunctionDeclarationInstantiation.
  4. Now in FunctionDeclarationInstantiation, reaching here, the current environment is the callee's environment created at the (2).
  5. FunctionDeclarationInstantiation step 11, we check hasParameterExpressions. If there's default parameter values, it becomes true.
  6. At step 21, we create the mutable binding of the all parameters before executing any of parameter assignments. So all the variables in the upper scope that name is the same to the parameters are hidden now.
  7. After that, at step 24 and 25, we initialize (assign) parameter values to the created mutable bindings. Reaching here, the current environment is the callee's environment.
  8. Evaluate the default parameters within the callee's environment. The callee's environment has the mutable bindings to the all parameters.

So when the given JS code is the following,

{
  var x = 20;
  function foo(x = function() { return x })
  {
    print(x());
  }
  foo()
}

The x inside the closure in the default parameter indicates the closure itself. So I think print(x()) will print the closure function itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment