Saturday, July 11, 2015

Lexical Scope and Closures

Lexical scope

Lexical scope means compile time scope. That means implicitly we can see what will be the scopes for each code. Most important thing to remember is, although javascript uses curly braces ({}), a new scope is created only when you create a new function.

Closure

Closure is when a function remembers it's lexical scope even when the function is executed outside that lexical scope.
In line 8, we pass "baz" function to "bam" function. Then "baz" function will execute outside of "foo" function. But still it has access to "bar" variable. That is a closure.

Friday, July 10, 2015

Javascript this keyword

Every function, while executing, has a reference it's current execution context, called this.

Default Binding

If you are in strict mode, default to this keyword is undefined. If  you are not in strict mode, default to this keyword is global object.
If we execute the code in strict mode, it will give following output.

Implicit Binding

In here this key word is automatically bind to the calling object.

Explicit Binding

If you use .call or .apply at the call side, the first parameter is this binding.

New keyword

When you put the new keyword, then function become a constructor call which means brand new object will be created and that object becomes the 'this' within the function call. In my previous post I explained about javascript new keyword.

Precedence of above rules with relates to this keyword


  1. Is it using new keyword?
  2. Is it using explicit binding?
  3. Is it using implicit binding?
  4. Is it using default binding?

Wednesday, July 8, 2015

Javascript new keyword

Following code should work fine.
But if we add new key word when we create an object then javascript runtime will automaticlly add highlighted code.