【发布时间】:2015-02-12 12:51:13
【问题描述】:
给定一个如下的 ES6 类,保持对传递给构造函数的数据的引用以便从实例方法中可用的最佳方法是什么?
到目前为止,我发现的最好的方法是手动将每个引用添加到构造函数中的某个实例属性。有没有更清洁/更简单的方法?
class Test {
constructor( {
option1 = 1,
option2 = 2
} = {} ) {
// What's the best way to keep a reference to
// the options on the instance?
this.options = {
option1,
option2
};
}
addOptions() {
return this.options.option1 + this.options.option2;
}
}
let t = new Test({
option1: 5
});
console.log(t.addOptions()); // 7
这是通过 6to5 运行的 above code 的链接。
【问题讨论】: