使用Google闭包编译器时,如何包含Ecmascript 6类?
例如,我有一个关于"stuff/dog.js"的课程:
class dog {
constructor() {
…
}
addLeg() {
this.legs++;
}
}
我想把它包含在"stuff/pound.js"中,这样我就可以写:
let rex = new Dog();
应该如何处理?我不能使用stuff.dog作为类名,所以将调用传递给goog.provide()似乎不是一个选项。
谢谢你的帮助!
编辑:使用最新版本的闭包编译器(20160517 1.0),这可以用普通的Ecmascript 6:处理
Animal.js:
export default class{
constructor(){
this.legs = [];
}
addLeg(legId){
this.legs.push( legId );
}
}
Dog.js:
import Animal from './Animal';
export default class extends Animal {
constructor(){
super();
[1,2,3,4].forEach(leg=>this.addLeg(leg));
console.log( 'Legs: ' + this.legs.toString() );
}
}
尽管它确实出于某种原因给了我一个警告:闭包编译器警告";错误的类型批注。未知类型…"当Ecmascript 6类扩展为时
ES6类可以分配给名称空间:
stuff.dog = class { }
new stuff.dog();
使用Jeremy和Chad的答案(谢谢,伙计们!)我设法使用类似的东西导入了我的类:
"stuff/dog.js":
goog.module('canine');
canine.dog = class {
constructor() {
…
}
addLeg() {
this.legs++;
}
}
"stuff/pound.js":
goog.require('canine');
let rex = new canine.Dog();
有一件事对我来说并不明显,那就是命名空间("canine")不需要与类名或文件名/路径有任何关系。