0
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??

coure2011
  • 37,153
  • 75
  • 206
  • 328

3 Answers3

1

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
  • 41,683
  • 10
  • 64
  • 84
1

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
  • 10,432
  • 5
  • 38
  • 57
1

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
  • 125,403
  • 30
  • 199
  • 217
  • 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. – Christian C. Salvadó Jul 28 '10 at 08:02