简体   繁体   中英

this keyword in a class method

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM