JavaScript closure and this object

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(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)
{
    //some code here
    return funcRef;
}

, ?

PS: , .

+5
2

:

return func(par);

( this), this === window undefined . , this .

:

myobj.func(par);  // this === myobj

func.call(myobj, ...)  // this === myobj

:

+4

this , .

, this , :

obj.myFunction();

, this window:

myFunction();

, , , , :

this.myOtherFunction();

, :

var f = obj.myFunction;
f();

call apply , ( ):

myFunction.call(obj);
+1

All Articles