2015-05-12 27 views
-1

我可以使用函數名稱在字符串中調用Require.js模塊中的函數嗎?使用字符串調用Require.js模塊中的函數var

define(['jquery', function($) { 

    var init = function() { 
     var elems = {}; 

     for(var x=0; x<$('.js-elem').length; x++) { 
      elems[x] = { 
       dom: { 
        el: $('.js-elem').eq(x) 
       }, 
       get animation() { 
        return this.dom.el.data('animation'); 
       } 
      } 

      setEvents(elems[x]); 
     } 
    }; 

    var setEvents = function(elem) { 
     elem.dom.el.on('click', function(e) { 
      console.log(elem.animation); // = String "anim1" 
      this[ elem.animation ](elem) // = window.anim1 (Out of require.js module scope) 
     }); 
    }; 

    var anim1 = function(elem) { 
     //... 
    }; 

    return { 
     init: init 
    }; 

}); 

回答

1

不,您不能通過字符串引用anim1。 「變量變量」僅適用於全局變量,但anim1不是全局變量。

查看"Variable" variables in Javascript?these search results的替代品。


注:this[ elem.animation ](elem)情況下,this並不是指window。它指的是elem.dom.el,處理程序綁定的元素。

但正如我所說,window[elem.animation]也不會工作,因爲anim1不是全球性的。