如何用变量加载方法?

时间:2014-01-25 01:13:00

标签: javascript jquery

我试图从用户输入中获取变量,并使用该变量作为方法名称。

我有类似

的东西

function test(){         this.control = $('。btn');         this.init()     }

test.prototype.init = function(){
    this.control.on('click', function(){
        var go = $(this).attr('id');  //go will have different direction  (up, down, right and left)
        this.go() //it gives me no go method error of course 
    })
}
  test.prototype.up = function(){

}
  test.prototype.down = function(){

}
  test.prototype.scrollRight = function(){

}
  test.prototype.scrollLeft = function(){

}


 var obj = new test();

如何在我的情况下根据元素id调用不同的方法?谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

使用bracket notation

this[go]()

所以

this.control.on('click', function () {
    var go = this.id; //go will have different direction  (up, down, right and left)
    this[go]() //it gives me no go method error of course 
})