0

Possible Duplicate:
Get property of object in JavaScript

var Terminal = function() {
  this.walk = function() {
    alert('hello');
  }
  this.go = 'walk';
  this.move = 'walk';
}

var term = new Terminal();
var fn = 'walk';
if (term.hasOwnProperty(fn)) {
  term.{fn};
}

How can I run the method term.walk() using the string 'walk'?

1

2 Answers 2

2

There are a couple of ways. The simplest is

term[fn]();

Or alternatively

var funcObj = term[fn];
funcObj.apply(term);
Sign up to request clarification or add additional context in comments.

Comments

1

Use term[fn] to access the <fn> property of term.

All properties can be accessed using object["propertyname"]. Globally defined properties/methods can be called through window["propertyname"].

There's only one occasion where variables cannot be accessed through obj["prop_name"]:

function foo(){
    var bar = 759;
     //There is no "obj" where obj.bar exists.
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.