Nate
Nate

Reputation: 919

'this' keyword within anonymous function

Can someone tell me what object this.onSubmit is referring to in the following code?

(function () {
    var _d = vjo.dsf.EventDispatcher;
    var _r = vjo.Registry;

    function $1(p0) {
        return function (event) {
            return this.onSubmit(p0, event);
        };
    };
})();

I apologise if there is not enough context attached to this example.

Upvotes: 2

Views: 580

Answers (3)

Douglas
Douglas

Reputation: 37761

Here it will be the window object. You can confirm this by adding console.log(this) on the line before.

Upvotes: 0

aefxx
aefxx

Reputation: 25249

Whatever object is being bound when the function is run.

Example:

(function() {
    ....
    function $1(p0) {
         return function (event) {
            return this.onSubmit(p0, event);
        };
    };

    var testObj = {
        foo: 'bar',
        onSubmit: function(x,y) { console.log(x,y); }
    };

    var func = $1('moep');

    func.call(testObj, 'hrhr'); // logs >> moep, hrhr

Upvotes: 2

I Hate Lazy
I Hate Lazy

Reputation: 48761

In JavaScript, the value of this is dynamically set. So to know its value, you need to know how the function is being called/used.

So the generic answer would be that this is referring to whatever was set as the this value of the execution context.

Upvotes: 5

Related Questions