I created a JavaScript class, and I would like to call a method inside every second, here is my code:
var MyClass = Base.extend({
myMethod: function() {
setTimeout(function(){
var mc = new MyClass();
mc.myMethod();
}, 1000);
}
});
var myGlobalClass = new MyClass();
myGlobalClass.myMethod();
Actually this code works, but I need to do a new MyClass() every time. I would had liked using myGlobalClass.
Is this possible ?
Just a precision this.myMethod() can’t work in this case, if you thought of that.
If you want to reffer to the value
myGlobalClassthen you can just do so directly from the functionThis works because Javascript doesn’t just look for locals defined in the current scope when resolving names. It looks at all of the parent scopes as well to resolve them. In this case
myGlobalClassis defined in the global scope. Name resolution begins in thesetTimeoutfunction callback and it won’t find it in the function, it will then searchmyMethod: function() {and won’t find it there, it will then look in the global scope and discovermyGlobalClass. It will resolve the name to this value