Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript this points to Window object

I have the following code. I expected to see "archive" object on my firebug console, but I see Window object. Is it normal?

var archive = function(){}

archive.prototype.action = {
    test: function(callback){
        callback();
    },
    test2: function(){
        console.log(this);
    }
}

var oArchive = new archive();
oArchive.action.test(oArchive.action.test2);
like image 956
Moon Avatar asked Apr 27 '10 08:04

Moon


People also ask

What does this point to in JavaScript?

In JavaScript, the this keyword allows us to: Reuse functions in different execution contexts. It means, a function once defined can be invoked for different objects using the this keyword. Identifying the object in the current execution context when we invoke a method.

What is window and this in JavaScript?

The window object is globalThe global object of JavaScript in the web browser is the window object. It means that all variables and functions declared globally with the var keyword become the properties and methods of the window object.

Is window a valid JavaScript object?

The window object is supported by all browsers. It represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object.


1 Answers

oArchive.action.test2 gets you a reference to a function that callback then points to, but that function is then called using callback(), which means it is not called as a method and hence this is the global object. The key point is that this is not bound to a function: it's determined by how the function is called.

In this case you could explicitly make this point to the action object (but not the archive object) by using the callback function's call or apply method:

test: function(callback) {
    callback.call(this);
},

To get it this to be the archive object instead, you'll need to pass the archive object in:

var archive = function(){}

archive.prototype.action = {
    test: function(callback, archive){
        callback.call(archive);
    },
    test2: function(){
        console.log(this);
    }
}

var oArchive = new archive();
oArchive.action.test(oArchive.action.test2, oArchive);
like image 56
Tim Down Avatar answered Oct 05 '22 21:10

Tim Down