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
https://forums.phpfreaks.com/topic/92829-objects-name-as-string/
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);
	    }
	}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.