Reputation: 659
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", "");
Upvotes: 0
Views: 62
Reputation: 5636
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");
};
Upvotes: 2
Reputation: 659
So the other properties of the context from which the closure is created are alive and can be called inside the closure but the only way to have them available outside is returning them.
function func(){
var context_field = "context_field";
var context_method = function(){
console.log("context method lives on");
};
func = function(param){
console.log(param + " func and " + context_field);
return context_method;
}
return func;
};
func()("Init finished and call");
func("Call again")();
Upvotes: 0