javascript - Getting around Babel remapping ES6 "this" to undefined -
i'm in process of moving codebase es6 classes.
i still dealing legacy jquery modules, have init functions attached them, called html. entry point of code looks this:
import * moduleone './module_one/module_one'; import * moduletwo './module_two/module_two'; import * modulethree './module_three/module_three'; import * modulefour "./module_four/module_four"; window.initjquery = (mod) => { eval(mod).init() } and in html:
<script>initjquery('modulefour')</script>
so works , modulefour.init() called. avoid use of eval if possible. problem babel remaps this undefined there no way me like:
var _this = this; window.initjquery = function(mod) { _this[mod].init(); } any ideas how resolve this?
those module names variables (in module scope), no properties of object. notice this undefined in modules in strict functions.
so you'll want put module objects on explicit object:
import * moduleone './module_one/module_one'; import * moduletwo './module_two/module_two'; import * modulethree './module_three/module_three'; import * modulefour "./module_four/module_four"; const modules = {moduleone, moduletwo, modulethree, modulefour}; window.initjquery = (mod) => { modules[mod].init() };
Comments
Post a Comment