【问题标题】:Why does super work with method syntax but not with property syntax?为什么 super 使用方法语法而不使用属性语法?
【发布时间】: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 语法,但这是故意的。

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    但是,如果我使用新的 ES6 方法语法......它工作得很好。

    这就是重点。 super 不允许在常规函数中使用。 specification 状态

    如果 FormalParameters Contains SuperProperty 为 true,则为语法错误。

    如果 FunctionBody Contains SuperProperty 为 true,则为语法错误。

    如果 FormalParameters Contains SuperCall 为真,则为语法错误。

    如果 FunctionBody Contains SuperCall 为真,则为语法错误。

    原因是只有方法的环境记录中设置了一个字段,这使得JS引擎可以解析super的值。方法声明不仅仅是语法糖。

    【讨论】:

    • 能否请您进一步详细说明您的问题,甚至提供一些超出规格的链接?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2018-07-31
    • 2016-06-22
    相关资源
    最近更新 更多