Closures In JavaScript

A “Closure” is an expression that can have free variables together with and environment that binds those variables.

Closures are nothing but inner functions.These are the function definitions that reside in another function.

A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. A closure has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

var HomoSapien = function() { this.name = ‘Kranthi’; }
var func = function() { alert(this.name); }
var c = new HomoSepian();
func.apply(t);

We can assign a different “this” object when calling an existing function. “this” refers to the current object, the calling object. With apply, we can write a method once and then inherit it in another object, without having to rewrite the method for the new object.Apply is very similar to call, except for the type of arguments it supports. Arguments array can be used instead of a named set of parameters. With apply, an array literal, for example, fun.apply(this, [name, value]), or an Array object, for example, fun.apply(this, new Array(name, value)) can be used.

Advertisements

, ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: