2014-01-25 40 views
1

我想從用戶輸入中獲取變量基礎並將該變量用作方法名稱。如何加載變量的方法?

我有類似

功能測試(){ 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

使用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 
})