在对象构造函数中使用“this"变量 [英] using the 'this' variable within object constructor
问题描述
我对在对象构造函数中调用this"变量时得到的结果有些困惑.
I'm a bit confused on the result I'm getting when calling the 'this' variable inside in object constructor.
function Slider(tag){
this.tag = document.querySelector(tag),
this.start = function(){
return this.interval;
},
this.interval = setInterval(function(){
console.log(this.tag); //undefined
console.log(this); //window object
}, 2000)
}
var route ={
init:function(){
mySlide = new Slider('slider');
mySlide.start();
}
}
document.addEventListener('DOMContentLoaded', route.init);
我正在记录标签 console.log(this.tag)
但是它返回 undefined
并且在 this
中记录 变量时>console.log(this)
它指的是窗口对象.
I'm logging tag console.log(this.tag)
however it's returning undefined
and when logging the this
variable inside console.log(this)
it refers to the window object.
问题:为什么 console.log(this.tag)
不返回所选元素?
Question: Why isn't console.log(this.tag)
returning the selected element?
推荐答案
这是因为当您将回调函数传递给 setInterval
时,它是在全局范围内调用的.这就是为什么 this
是 window
.
This is because when you pass a callback function to setInterval
, it's called in the global scope. That's why this
is window
.
您可以使用函数.bind()
将函数的上下文设置为您的 this
对象并使其按照您的意愿工作.
You can use Function.bind()
to set the context of the function to your this
object and make it work as you want.
this.interval = setInterval(function(){
console.log(this.tag);
}.bind(this), 2000);
另外,我只想指出 mySlide.start();
什么都不做.当您调用 new Slider('slider')
时,即设置了间隔时间.您的 mySlide.start();
只返回 intervalID(仅用于 clearInterval()
).实际上,由于您甚至没有使用 mySlide.start();
的返回值,因此调用它是没有用的.
Also, I just want to point out that mySlide.start();
does nothing. When you call new Slider('slider')
, that's when your interval is set. Your mySlide.start();
just returns the intervalID (which is only used for clearInterval()
). Actually since you are not even using the return value of mySlide.start();
, calling it is useless.
更新:另一种解决方案是在构造函数中使用 var self = this;
,然后在 setInterval()
中使用 self
:
UPDATE: Another solution is to use var self = this;
in your constructor function and then use self
inside setInterval()
:
function Slider(tag){
var self = this;
this.tag = document.querySelector(tag),
this.interval = setInterval(function(){
console.log(self.tag);
}, 2000);
}
更新:如果您使用的浏览器支持 箭头函数",那么你可以这样做:
UPDATE: If you are on a browser that supports "arrow functions", then you can do this:
this.interval = setInterval(() => {
console.log(this.tag);
}, 2000);
这篇关于在对象构造函数中使用“this"变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!