Adam
Adam

Reputation: 9049

Javascript executing function with a string

I'm creating a prototype class like so, but I want to call a function using a string as the function name. I found the windowname; example somewhere, but it's not working in my case.

function someObj() {

  this.someMethod = function() {
    alert('boo'); 
    name = "someOtherMethod";
    window[name]();
  }

  var someOtherMethod = function() {
    alert('indirect reference');
  }

}

Upvotes: 0

Views: 69

Answers (4)

Dennis
Dennis

Reputation: 32598

Create your own hash of methods:

function someObj() {

  this.someMethod = function() {
    alert('boo'); 
    name = "someOtherMethod";
    methods[name]();
  }

  var methods = {
    someOtherMethod : function() {
        alert('indirect reference');
    }
  };
}

Your variable is local to your function so it won't be in window. Even if you are working in the global scope, it is better to use your own object than it is to rely on window so you can avoid name collisions.

Upvotes: 0

AbdulFattah Popoola
AbdulFattah Popoola

Reputation: 947

someOtherMethod is hidden from window and exists only in the scope of your prototype.

Try to move it out.

function someObj() {
    this.someMethod = function() {
       alert('boo'); 
       name = "someOtherMethod";
       window[name]();
     }
}

var someOtherMethod = function() {
    alert('indirect reference');
}

Although it is a bad idea using globals.

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

This is because "someOtherMethod" is not a member of the window object as it defined inside the someObj function.

Upvotes: 1

I Hate Lazy
I Hate Lazy

Reputation: 48761

window is only for global variables.

You can't access local variables via a string, unles you use eval, which is almost always a bad idea.

One alternate way is to use an object. This allows you to look up properties using a string.

function someObj() {

  var methods = {};

  methods.someMethod = function() {
    alert('boo'); 
    var name = "someOtherMethod";
    methods[name]();
  }

  methods.someOtherMethod = function() {
    alert('indirect reference');
  }

}

Upvotes: 0

Related Questions