0

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

}
1
  • 1
    You cannot access local variables via a string containing their name. You can only access object properties this way, so make someOtherMethod an object property by either assigning it to this or window or any other object. Commented Sep 29, 2012 at 18:49

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

}

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.