Ashish Kalra
Ashish Kalra

Reputation: 11

Closure without nested function

Up till now my understanding of closures is, if a function returns a function, then the returned function(object) remembers the context of its (lexical) parent function scope and I was thinking of a scenario where a closure can be achieved without implementing a nested function.

The code below is a perfect example of this. What I have done here is:

I have used a constructor to create objects and I have used the parameters passed to it in the method toString() defined inside.

Now I have created two objects and both objects have their separate copies of id, name, madeInYear.

Please note I could have achieved the same result by using productId, productName, productOriginDate but just to see closure, I have written the code snippet like this.

Another interesting thing I have observed is I can access productId but not id. Does that means they are not being created in the context of object ?

function f1(id,name,madeInYear)
{
this.productId=id;
this.productName=name;
this.productOriginDate=madeInYear;

this.toString=function()
{
    console.log("Function Parameters:"+id+" "+name+" "+madeInYear);
    console.log("Objects Method:"+this.productId+" "+this.productName+" "+this.productOriginDate);
}

}

var obj1=new f1(1,"Parker Pen","2001");
var obj2=new f1(2,"Jetter",2000);

obj1.toString();
obj2.toString();
obj1.productId;
obj2.productId;

Output

Function Parameters:1 Parker Pen 2001

Objects Method:1 Parker Pen 2001

Function Parameters:2 Jetter 2000

Objects Method:2 Jetter 2000

1

2

Upvotes: 0

Views: 359

Answers (1)

Touffy
Touffy

Reputation: 6561

A closure is defined as accessing local variables from the lexical context where a function was defined, when that function is called outside of that context.

So there has to be a function to create a proper closure. You could replace the outer function with something else that has local variables, which is possible in ES6 with block scoping and let declarations:

{
    let local = 3
    function f() {
        return local
    }
}
console.log(local) // undefined
console.log(f())   // 3

Upvotes: 2

Related Questions