【发布时间】:2016-11-11 03:40:59
【问题描述】:
我正在运行节点 6.9.1。
我这样定义一个基础对象:
const base = {
value : 10,
getFinalValue : function() {
return this.value
}
}
现在我想为getFinalValue 方法定义一个修饰符。
我的第一次尝试是使用新的 ES6 super 关键字:
const modifier = Object.create(base)
modifier.getFinalValue = function () {
return super.getFinalValue() + 20
}
但是,上面的代码给了我以下错误:
> SyntaxError: 'super' keyword unexpected here
我试过的:
// With Object.defineProperties within Object.create
const modifier = Object.create(base, {
getFinalValue : {
value : function () {
return super.getFinalValue() + 20
}
}
})
// And with Object.setPrototypeOf
const modifier = {
getFinalValue : function () {
return super.getFinalValue() + 20
}
}
Object.setPrototypeOf(modifier, base)
结果是同样的错误。
但是,如果我使用新的 ES6 方法语法:
const modifier = {
getFinalValue() {
return super.getFinalValue() + 20
}
}
Object.setPrototypeOf(modifier, base)
modifier.getFinalValue() // 30 (yay!)
效果很好。
如果我使用Object.getPrototypeOf 而不是super,它可以使用属性语法:
const modifier = {
getFinalValue: function () {
return Object.getPrototypeOf(this).getFinalValue.call(this) + 20
}
}
Object.setPrototypeOf(modifier, base)
modifier.getFinalValue() // 30 (Yay!)
谁能解释一下为什么会这样?
P.S.:是的,我知道我在混合 ES5 和 ES6 语法,但这是故意的。
【问题讨论】: