绕过Babel重新映射ES6“this”;未定义的
Getting around Babel remapping ES6 "this" to undefined
我正在将代码库移动到ES6类。
我仍然在处理一些遗留的jQuery模块,其中有init
函数附加到他们,这是从html调用。代码的入口点如下所示:
import * as moduleOne from './module_one/module_one';
import * as moduleTwo from './module_two/module_two';
import * as moduleThree from './module_three/module_three';
import * as moduleFour from "./module_four/module_four";
window.initjQuery = (mod) => {
eval(mod).init()
}
在HTML中:
<script>initjQuery('moduleFour')</script>
这样就可以工作了,moduleFour.init()被正确调用了。但是如果可能的话,我希望避免使用eval。问题是,Babel将this
重新映射到undefined
,所以我没有办法做这样的事情:
var _this = this;
window.initjQuery = function(mod) {
_this[mod].init();
}
有什么办法解决这个问题吗?
这些模块名只是变量(在模块范围内),不是任何对象的属性。请注意,模块中的this
和严格函数中的undefined
一样。
所以你要把这些模块对象放在一个显式对象上:
import * as moduleOne from './module_one/module_one';
import * as moduleTwo from './module_two/module_two';
import * as moduleThree from './module_three/module_three';
import * as moduleFour from "./module_four/module_four";
const modules = {moduleOne, moduleTwo, moduleThree, moduleFour};
window.initjQuery = (mod) => {
modules[mod].init()
};
相关文章:
- this.router在AngularJS 2中未定义
- React+Meteor:this.ops返回未定义
- `当使用箭头函数时,“开发工具”中未定义“this”
- jQuery$(this)引用未定义
- this.defaultValue 返回 select 元素的未定义
- Alt flux action:_this.actions未定义,即使调用了this.generateActions
- $(this).attr({class:“activeTab”});不起作用,因为这是未定义的
- $(this)抛出“;未定义的“;但这是按预期进行的
- jqueryui:"类型错误:this.menu.element未定义"
- this.value在<td>标记显示未定义
- $(this)返回'未定义'
- TypeError:this.clusterer在Rails模型名称更改后未定义
- this._id流星中未定义
- Angular ES6,THIS,Scope和EL在JQLITE点击事件中全部未定义
- this.userId 在 Meteor.publish 中返回未定义
- 为什么我需要将“var value = val;”更改为“this.value = val;”,这样我就不会收到“未定义
- ReactJS - {this.props.children} 是未定义的
- 为什么 this.name 未定义
- 当从另一个上下文中调用方法时,' this '未定义
- 绕过Babel重新映射ES6“this”;未定义的