[英]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. 这是因为init不是“类方法”-它是您在构造函数中定义和调用的函数。 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': 您将需要在mC函数的“ this”的上下文中调用init函数:
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' 或者,您需要使“ init”成为this或this.prototype的成员,这会自动将其所属的对象用作“ this”
You may want to google about JavaScript's this keyword if this confuses you :) 如果这使您感到困惑,您可能想在Google上搜索JavaScript的this关键字
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. 您将init定义为一个函数,然后在全局空间中对其进行调用,这就是为什么要完成您的工作的原因。 You didn't attach it to the mC class. 您没有将其附加到mC类。
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). 由于init
是mC
的变量,它将共享其作用域(当前是全局作用域,它也是window
对象)。
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. 然后, this
init
内部init
将引用您的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.