异步加载文件后的访问类正在试图异步加载文件并访问类,但我不能这样做。使用promise()ECMAScript 6
我main.js
具有基本类
console.log("=============in main script=================")
class test{
constructor(auth_key,auth_secret){
this.auth_key = auth_key;
this.auth_secret = auth_secret;
console.log("============In class test============");
}
init(){
console.log("============In init function============"+this.auth_key);
}
}
试图访问index.html
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
function sttAsyncLoad(){
console.log("===========loading script asynchronously============");
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = "src/main.js";
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
sttAsyncLoad();
let sObj = new test("test","test11");
</script>
</body>
</html>
输出得到错误Uncaught ReferenceError: test is not defined
类。
任何人都可以请帮助我。
见,所有的浏览器不支持ES6的所有功能。所以你必须使用像TypeScript或Babel这样的编译器。你可以在[Caniuse.com](http://caniuse.com/#search=class) –