Reputation: 555
Ok I have a problem in JavaScript I have created an Function Constructor and added a properties and methods one method has when it's called to work with the object environment methods as a basic example as my constructor is too complex.
function Construct(){
this.alert = 'test1';
this.replace = '';
this.interval;
this.run = function(){
console.log(this);//echo the constructor
this.interval = setInterval(function(){
console.log(this);//echo the window object
alert(this.alert);
this.replace = '';
}
};
}
This fails if you have read the code you must understand why.
how could I pass the constructor object (this) to the set interval function?
I have tried using external functions and pass this as an arguments but it fails miserably as replace is still as it is and it is runes only once why?
Please Help.
Thank you.
Upvotes: 1
Views: 187
Reputation: 219930
Create a local self
variable, and set it to this
, so that you can use that in your nested function:
function Construct () {
this.alert = 'test1';
this.replace = '';
this.interval;
this.run = function () {
var self = this;
this.interval = setInterval(function () {
self.replace = '';
}, 500);
};
}
Upvotes: 2