【发布时间】:2015-04-05 22:11:31
【问题描述】:
我想使用Object.assign 临时用新方法“升级”一个对象,然后在我用完这些方法后删除它们。举个例子就明白了:
假设我们有一个可以计算数组平均值的 mixin:
var ArrayUtilMixin = {
avg() {
let sum = this.reduce( (prev, v) => {return prev + v}, 0);
return sum / this.length;
}
};
我们的客户端代码是这样使用的:
let myArr = [0,3,2,4,88];
// now I am in a context where I want to average this array,
// so I dynamically add the ability with Object.assign
Object.assign(myArr, ArrayUtilMixin);
let avg = myArr.avg();
// do some stuff here with the average
// now we're done, we want declutter the myArr object
// and remove the no longer needed avg() method
Object.unassign(myArr, ArrayUtilMixin); // <-- CAN WE DO THIS SOMEHOW?
有没有办法做到这一点?如果不是,我是否使用了我真正想要的错误语言功能——在运行时动态添加和删除对象方法的能力,具体取决于上下文。
【问题讨论】:
-
您可以简单地遍历
ArrayUtilMixin的属性并将它们从myArr中删除。这仅在分配ArrayUtilMixin不会覆盖myArr的任何属性时才有效。另一种有趣的方法是将ArrayUtilMixin插入myArr的原型链。但这可能不适用于原生对象。
标签: ecmascript-6