I thought I had a reasonable understanding of the object thisin JavaScript. When you work with objects, callbacks, and both events and handlers, I have not had a problem with it since time immemorial. Now, however, everything has changed.
I fell on my heels in love with JavaScript. Pure JS, i.e. not jQuery, prototype.js, dojo ... So, naturally, I took the use of closures. In some cases, however, it thiscatches me here. Take this snippet for one:
function anyFunc(par)
{
console.log(this);
}
function makeClosure(func)
{
return function(par)
{
return func(par);
}
}
var close = makeClosure(anyFunc);
close('Foo');
var objWithClosure = {cls:makeClosure(anyFunc),prop:'foobar'};
objWithClosure.cls(objWithClosure.prop);
var scndObj = {prop:'Foobar2'};
scndObj.cls = makeClosure;
scndObj.cls = scndObj.cls(anyFunc);
scndObj.cls(scndObj.prop);
In all three cases, it is thisregistered as a window object. This, of course, is an easy solution:
function makeClosure(func)
{
return function(par)
{
return func.call(this,par);
}
}
This fix works, I put it here so that people donβt respond to it without explaining what I need to know: why does it behave the way it is here?
, , . , :
, this , . logging this makeClosure , , window. , this . ?
, , , , anyFunc , window.anyFunc. :
function makeClosure(func)
{
var theFunc = func;
return function(par)
{
theFunc(par);
}
}
this , : ? (theFunc [this > private: theFunc]?), , -, JS, , ...
, , - , ;)
/ 2
, .
, . , : , , :
function makeClosure()
{
function fromThisFunc()
{
console.log(this);
}
return fromThisFunc;
}
var windowContext = makeClosure();
windowContext();
var objectContext = {cls:makeClosure()};
objectContext.cls();
, anyFunc ββ , this . , , - .
, , globalVar, [[scope]], , Activation/Variable, , ( ). Activation/Variable , , globalVar, [[scope]] , .
, , :
function fromThisFunc()
{
console.log(this);
}
function makeClosure(funcRef)
{
return funcRef;
}
, ?
PS: , .