简体   繁体   中英

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

You should use this instead.

this[ where ]();

jsFiddle demo

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. Eg ['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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM