tags:

views:

37

answers:

3
var mC = function(map){
    var init = function(iMap){
        alert("Init " + this + " with");
    }
    init(map);
};
var m = new mC({});

why i am getting value of this as [object window]? Is it a window object??

+1  A: 

It's because init is not a "class method" - it's a function you're defining and calling inside a constructor. That doesn't make it special of other functions in any way.

You will need to call the init function in the context of the mC function's 'this':

init.call(this);

Or, you will need to make 'init' a member of this or this.prototype, which will automatically use the object it's a member of as 'this'

You may want to google about JavaScript's this keyword if this confuses you :)

Jani Hartikainen
+1  A: 

What else would you be expecting to get?

You defined init as a function and then called it in the global space so that is why you got what you did. You didn't attach it to the mC class.

spinon
+1  A: 

Yes! Because init is a variable of mC, it will share its scope (which currently is the global scope, which is also the window object).

However. If you changed to the following:

var mC = function(map){
    this.init = function(iMap){
        alert("Init " + this + " with");
    }
    this.init(map);
};
var m = new mC({});

Then this inside init would be a reference to your instance.

David Hedlund
It's about how the function is invoked, e.g. `init();`, has no *base object* (is not bound as a property of any accessible object), so the `this` value within it will point to the global object, no matter where in the *scope* chain you are.
CMS