Bogdan Volosincu Bogdan Volosincu - 4 months ago 9
Javascript Question

What happens with the other properties of a JavaScript closure context ?

I will try to be as clear as possible on my question so:

There are a lot of blogs and tutorials that explain closures but what i didn't manage to figure out is what happens with other properties of the context from which the closure get's created ? jsFiddle

function func(){

this.context_field = "context_field";
this.context_method = function(){
console.log("context method");
};


func = function(param, change){
if(typeof(change) === 'undefined'){
//......
console.log(param + " " + context_field + " from original func - closure\n\n");
//.....
}
return func;
};

func()("Init finished and call");
func("Call again", "");

Answer

In this example there is no context created, because the keyword 'this' inside the function 'func' refers to window (global Object).

To create a context declare vars like this:

var context_field = "context_field";
var context_method = function(){
    console.log("context method");
};
Comments