Jump to content

Object's name as string


Onetoomanysodas

Recommended Posts

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);
    }
}

Link to comment
Share on other sites

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);
	    }
	}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.