setInterval inside a class

J

Jim Red

hello, how can i set an interval inside a class

exmpl.

var Class = (function() {
var interval = undefined;

function initInterval(instance) {
interval = setInterval("doSomething", 1000, instance);
}

function doSomething(instance) {
alert(instance.message);
}

function Constructor() {
this.message = "hello world";
}

Constructor.prototype.init = function() {
initInterval(this);
}

return Constructor;
})();


is not working correct. doSomething is not known. i think, setInterval
is not inside the class, so doSomething is private and unknown for the
interval

can anyone help?

//jim
 
Y

Yann-Erwan Perio

Jim Red wrote:

Hi,
var Class = (function() {
var interval = undefined;

function initInterval(instance) {
interval = setInterval("doSomething", 1000, instance);
}

function doSomething(instance) {
alert(instance.message);
}

function Constructor() {
this.message = "hello world";
}

Constructor.prototype.init = function() {
initInterval(this);
}

return Constructor;
})();

When using a string for the first argument of setInterval, the string is
evaluated in the global context; however "doSomething" is not global, it
is a local member of Class. You should therefore use a function rather
than a string for you first argument, since nested function still have
access to outer variables (closures), and you can then have a better
control of scopes. See below.


---
var MyClass = (function() {
var interval;

function initInterval(instance) {
interval = setInterval(
function() {
instance.doSomething();
},
2000
);
}

function Constructor() {
this.message = "hello world";
}

Constructor.prototype.init = function() {
initInterval(this);
}

Constructor.prototype.doSomething = function() {
alert(this.message);
}

return Constructor;
})();

var foo=new MyClass();
foo.init();
 
T

Thomas 'PointedEars' Lahn

Jim said:
hello, how can i set an interval inside a class
[...]

Note that the version of J(ava)Script you are referring to does not support
classes, it supports (only) prototype-based inheritance. Your source code
presents a so far unnecessary encapsulation of the methods of a prototype
within a so-called "constructor function" -- it is a factory which is not
needed here nor does help anything to keep the global scope sober.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top