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);
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.
Question: Why isn't console.log(this.tag) returning the selected element?
thisfrom the surrounding scope. You can either usebindor assign a variablevar self = this;in the surrounding scope.