Onetoomanysodas Posted February 25, 2008 Share Posted February 25, 2008 I need a function to be able to set a delayed event (setTimeout) to run itself within a class which means it has to be passed as a string, making arguments.callee useless. Is there any way to get the object's name like "test" in my example below from within the class or will I just have to pass the name in an argument? Does anyone know an efficient way of implementing window's globally stored variables to get an object's name as a string? var test = new MyClass(); test.start(); function MyClass() { this.start = function() { this.action(); } this.action = function() { // method body if(recurse == true) setTimeout(test_object_name+".action()", 5); } } Quote Link to comment Share on other sites More sharing options...
fenway Posted February 25, 2008 Share Posted February 25, 2008 Like with eval(). Quote Link to comment Share on other sites More sharing options...
emehrkay Posted February 25, 2008 Share Posted February 25, 2008 setTimeout() is its own object and has its own scope for the keyword "this" what you need to do is pass a function to the setTimeout function that binds MyClass to it (applies the this in MyClass to the function passed in) using your code, you can do it like this: function MyClass() { this.start = function() { this.action(); } this.action = function() { // method body var method = this.action(); var class = this; if(recurse == true) setTimeout( function(){ method.apply(class) } , 5); } } Or you could use JS the way it is "supposed" to be used and prototype the function method and add a bind function Function.prototype.bind = function(object) { var method = this; return function() { method.apply(object, arguments); } } function MyClass() { this.start = function() { this.action(); } this.action = function() { // method body var method = this.action(); var class = this; if(recurse == true) setTimeout(this.action.bind(this), 5); } } Quote Link to comment Share on other sites More sharing options...
emehrkay Posted February 25, 2008 Share Posted February 25, 2008 im sorry, do not do var method = this.action(); //this will execute the action method and set the return to method do it this way var method = this.action; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.