使用字符串 var 在 Require.js 模块中调用函数
Calling a function inside Require.js module with string var
我可以在 Require.js 模块中使用字符串中的函数名称调用函数吗?
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
};
});
不,您不能通过字符串引用 anim1
。 "Variable variables" 仅适用于全局变量,但 anim1
不是全局变量。
请参阅 "Variable" variables in Javascript? or these search results 了解替代方案。
注:在this[ elem.animation ]( elem )
的情况下,this
不是指window
。它指的是 elem.dom.el
,处理程序绑定到的元素。
但正如我所说,window[elem.animation]
也不起作用,因为 anim1
不是全局的。
我可以在 Require.js 模块中使用字符串中的函数名称调用函数吗?
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
};
});
不,您不能通过字符串引用 anim1
。 "Variable variables" 仅适用于全局变量,但 anim1
不是全局变量。
请参阅 "Variable" variables in Javascript? or these search results 了解替代方案。
注:在this[ elem.animation ]( elem )
的情况下,this
不是指window
。它指的是 elem.dom.el
,处理程序绑定到的元素。
但正如我所说,window[elem.animation]
也不起作用,因为 anim1
不是全局的。