kasper Taeymans
kasper Taeymans

Reputation: 7026

javascript: call method in an object from string

I'm trying to make a controller for my app. I'm not able to do what I want and I don't understand why :-( I'm not a javascript expert so probably I'm doing something that is not allowed. Error from firebug:

TypeError: window[("Controller." + where)] is not a function

The error is clear, but why is this happening?

jsFiddle: http://jsfiddle.net/TB8yr/1/

var Controller= function(){
    this.currentpage='home';

}

Controller.prototype.route=function(where){

    window["Controller."+where]();
};

Controller.prototype.goHome=function(){
    alert('route gohome');

}

Controller.prototype.goBack=function(){
    alert('route goback');

}

//////
test=new Controller();
test.route('goHome');

Upvotes: 0

Views: 68

Answers (2)

jbabey
jbabey

Reputation: 46647

You have a few problems:

First, jsFiddle runs all of its code inside an IIFE. Declaring a variable in the javascript section will not append it to the window object of the page.

Second, you can't nest properties via dot notation in bracket notation like that. E.g. ['parent']['child'], not ['parent.child'].

Lastly, you're trying to call an instance method (goHome) on the constructor function, not an instance. You should be using this inside the prototype methods to refer to the instance.

Working example: http://jsfiddle.net/TB8yr/4/

var Controller= function(){
    this.currentpage='home';    
}

Controller.prototype.route=function(where){
    this[where]();
};

Controller.prototype.goHome=function(){
    alert('route gohome');    
}

Controller.prototype.goBack=function(){
    alert('route goback');    
}

test = new Controller();
test.route('goHome');

Upvotes: 2

antyrat
antyrat

Reputation: 27765

You should use this instead.

this[ where ]();

jsFiddle demo

Upvotes: 4

Related Questions