This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I would like to start a setInterval method in javascript every time I instantiate a class (I know, I shouldn't call it class in javascript, ...). The setInterval is calling the class method update every 500 milliseconds. Here is my code:
function Test(a) {
this.a = a;
this.b = 0;
this.interval = setInterval(this.update, 500);
};
Test.prototype.update = function() {
console.log(this.b);
this.b += 1;
if (this.b > 10) clearInterval(this.interval);
};
But when I instantiate the class with var mytest = new Test(1), the class property b seems to be undefined in the first call and NaN subsequently (because adding 1 to undefined gives NaN). Why b is not 0in the first call?
The scope of this changes when setInterval fires. this will be window. To maintain the scope, you can use bind.
setInterval(this.update.bind(this), 500);
Related
This question already has answers here:
Functions that return a function
(10 answers)
Closed 3 years ago.
I was taking a small test online and there was this code:
function getFunc() {
var a = 7;
return function(b) {
alert(a+b);
}
}
var f = getFunc();
f(5);
I would like to know why I can't call getFunct(5) directly for example.
I don't understand the last two lines.
Why do I need to assign the function to a variable. What happens when doing f(5)?
How does JS interpret that the 5 is a variable for the inner function and not the outer?
You could call the inner function immediately after calling the first one, because the first call returns a function and the second call gives the result.
function getFunc() {
var a = 7;
return function(b) {
console.log(a + b);
}
}
getFunc()(5);
By assigning getFunc() to the variable f you actually assigned the return value i.e. inner function to f since that's what getFunc is returning. The braces () make a difference here.
However had it been f = getFunc i.e. without the braces, that would imply f is an alias for getFunc and you'd have to do f()(5) in that case.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
I don´t get why "this" in this case returns "NaN" :
function Counter() {
this.num = 0;
this.timer = setInterval(function add() {
this.num++;
console.log(this.num);
}, 1000);
}
And in this one it refers to "this.value":
function foo() {
this.value = 'Hello, world';
this.bar = function() {
alert(this.value);
}
}
var inst = new foo();
inst.bar();
I get that in the first case "this" is pointing to the Window object, I just don´t get why that´s the case.
Inside setInterval this will be completely new and it will have no idea about Counter. You can use bind to pass the context this to setInterval
function Counter() {
this.num = 0;
this.timer = setInterval(function add() {
this.num++;
console.log(this.num);
}.bind(this), 5000);
}
Counter()
Alternatively you can also use arrow function
function Counter() {
this.num = 0;
this.timer = setInterval(() => {
this.num++;
console.log(this.num);
}, 5000);
}
Counter()
The setInterval function barely looks like this:
function setInterval(callback, time, ...args) {
// native complicated code
callback(...args);
}
What matters here is the call (callback(...)), as JS determines the context by how you are calling the function. In your second example the context of bar is inst as you call it as inst.bar(), so you directly tell js what this is. If you call a function direclty, e.g.
const bar = inst.bar;
bar(); // call without context
you don't specify a context, and therefore this defaults to window
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
Hi I'm trying to create an object in jQuery and everything is working fine but somehow I cannot pass some necessary properties beyond the setInterval function bc when I test it it always pops "undefined". Here is the draft code of that I have.
Thanks in advance!!
function MyFunction(var1){
this.var = var1;
this.var2 = 2;
this.pause = 3000;
this.slideOn();
}
MyFunction.prototype.slideOn = function(){
alert(this.var); //alerts the value
setInterval(function(){ //doesnt work and it alerts "undefined"
alert(this.var2),1000,function(){}
},this.pause // works again with no hassle
};
When you use "this" inside some callback function, it uses function scoped "this". So, try setting an "outer this":
function MyFunction(var1){
this.var = var1;
this.var2 = 2;
this.pause = 3000;
this.slideOn();
}
MyFunction.prototype.slideOn = function(){
var _this = this;
alert(_this.var); //alerts the value
setInterval(function(){ //doesnt work and it alerts "undefined"
alert(_this.var2),1000,function(){}; //100 and function are senseless
},_this.pause); // works again with no hassle
};
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
My code creates a dispatcher from constructor ColorDispatcher. After window.onload, dispatcher.hoverOutHandler is regularly called after 1.5 sec. when changeBGColor called, the typeError described in the title shows; However I really cannot figure out why.
var ColorDispatcher = function() {
this.changeColorTimerID = 0;
this.rgbColorArray = new Array(0, 0, 0);
};
ColorDispatcher.prototype = {
hoverOutHandler: function() {
this.changeColorTimerID = window.setInterval(this.changeBGColor, 1500);
},
changeBGColor: function() {
//something went wrong here.
alert(this.rgbColorArray[0]);
},
};
var dispatcher = new ColorDispatcher();
window.onload = dispatcher.hoverOutHandler();
Change the following line:
this.changeColorTimerID = window.setInterval(this.changeBGColor.bind(this),1500);
setInterval called the function on the window scope therefor the array wasn't found. With .bind you can bind a function to a scope (in this case this).
This question already has answers here:
What does 'var that = this;' mean in JavaScript?
(6 answers)
Closed 8 years ago.
I'd like to know and understand the different between this and that, and when I have to use it.
I ready many post and many tutorial but I don't understand yet
this is my class
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function () {
console.log(this.member); // foo
console.log(that.member); // foo
return dec() ? that.member : null;
};
}
New
var myContainer = new Container('foo');
myContainer.service()
Calling myContainer.service() will return 'abc' the first three times it is called.
After that, it will return null
Why i have to do var that = this ??
this is a variable that gets the context of the current function (which depends on how it was called).
that has no special meaning. It is just a variable to which a value has been assigned.
In this particular case, that is assigned the value that this has while the Container is running, and is used inside the service function (but still has the value that is the context of the call to Container. Since service is a different function, its value of this could be different.
Normally, for this particular design of function, Container would be called as a constructor function (so this would be the instance object of Container) and then service would be called in the context of that instance object so you could use this instead of passing the value around via that. I have no idea why the author of that code chose to use that here.