Javascript Functions, scoping, and changing context

Since no inner function is declared, this function object is bound to the global scope.

In the above code:

  • global scope has one variable globalVariable.
  • However in globalFunction function object, notice notice we have a inner function, and thus, each function’s this scope is bound to itself.
  • the inner function cannot read the outer scope’s variable and thus both innerVariable and globalVariables are undefined.
  • In globalFunction’s globalVariable is undefined because it is not declared in its this scope

Thus, in the example, there are separate ‘this’ objects bound to each invoking function.

Unbeknownst to many Javascript developers, there is an arguments object created within a function. It is an Array-like object (only having the property length). Arguments has three main properties, namely, callee (the invoking method), length, and caller (the reference to invoked function).

Declaring a variable arguments inside a function replaces/overrides the primary arguments object.

Call, Apply

Both call and apply are used to invoke a method on an object.

Bind

The bind method is used to invoke methods while explicitly specifying this.