如何在Javascript ES6中动态加载类

时间:2016-04-12 18:11:40

标签: javascript

在Javascript ES6中,我们如何动态加载类?

我正在构建资产管理器,并且在下面的类' 中有一个load()方法,它使用JQuery函数{{1}加载文件 security.js 。尽管如此,文件 security.js 确实会加载,因为我能够看到Ajax调用及其响应。但是,我无法通过

初始化该类

既不是

$.getScript()

,也不

yellow = new asset_security();

我的例子:

let script = new window['asset_'+s['screen']]();

我从控制台class asset { constructor() { this.include = ['general','header','menu']; this.css = []; this.js = []; // Create Defaults for the app this.css['general'] = []; this.js['general'] = []; this.css['header'] = []; this.js['header'] = []; this.css['menu'] = []; this.js['menu'] = []; // this.css['general'][this.css['general'].length] = 'initial.css'; // this.js['general'][this.js['general'].length] = 'controller/initial.js'; // this.css['header'][this.css['header'].length] = 'header/header.css'; // this.js['header'][this.js['header'].length] = 'header/controller/header.js'; // this.css['menu'][this.css['menu'].length] = 'menu/header.css'; // this.js['menu'][this.js['menu'].length] = 'menu/controller/menu.js'; } load() { let s = new status(0); /** * @param data ~ Content of the script returned * @param textStatus ~ Verbal response to success or fail * @param browser ~ browser.status returns the 200/404/500 statuses */ $.getScript( "/js/asset/"+s['screen']+'.js', function( data, textStatus, browser ) { var exist = false; try { exist = (typeof 'asset_'+s['screen'] === 'function'); } catch (e) {} if ( exist ) { //TODO: figure out how to load class dynamically /* let script = new window['asset_'+s['screen']](); script.load(); script.render(); */ } }); }

获得的回复

state :ReferenceError: asset_security is not defined运行后初始化类的正确方法是什么?

这就是asset_security类的样子:

$.getScript()

enter image description here

1 个答案:

答案 0 :(得分:0)

我看到您正在从某个外部资源下载JavaScript文件后尝试加载它。您可以创建一个脚本标记并通过它加载JavaScript类文件。

示例:

if ( file_exists ) {
   var imported = document.createElement('script');
   imported.src = '/path/to/imported/script';
   document.head.appendChild(imported);
}