this keyword in a class method
var mC = function(map){
var init = functi开发者_StackOverflowon(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??
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.
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 :)
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.
精彩评论