【问题标题】:ES6 Classes with Inheritance issue and Traceur Not Showing Compiled Code具有继承问题和 Traceur 未显示编译代码的 ES6 类
【发布时间】:2015-02-21 17:30:51
【问题描述】:

我正在试验 ES6。特别是类和继承。在Apple 类中,它扩展了Polygon。我想扩展Polygon 的方法sayName() 并让它转到console.log。

当我通过 traceur 运行它时,我得到 undefined for console.log(foo);

class Polygon {
  constructor(height, width) { //class constructor
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }

  sayName() { //class method
    return 'Hi, I am a', this.name + '.';
  }
}


class Apple extends Polygon {
    constructor(length) {
    super(length, length); //call the parent method with super
    this.name = 'apple';
  }

  sayName() {
    var foo = super();
    console.log(foo);
  }
}


let d = new Apple(5);
d.sayName();

追踪者:

System.register("class", [], function() {
  "use strict";
  var __moduleName = "class";
  function require(path) {
    return $traceurRuntime.require("class", path);
  }
  var Polygon = function Polygon(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  };
  ($traceurRuntime.createClass)(Polygon, {sayName: function() {
      return 'Hi, I am a', this.name + '.';
    }}, {});
  var Apple = function Apple(length) {
    $traceurRuntime.superConstructor($Apple).call(this, length, length);
    this.name = 'apple';
  };
  var $Apple = Apple;
  ($traceurRuntime.createClass)(Apple, {sayName: function() {
      var foo = $traceurRuntime.superConstructor($Apple).call(this);
      console.log(foo);
    }}, {}, Polygon);
  var d = new Apple(5);
  d.sayName();
  return {};
});
System.get("class" + '');
  1. 如何在Apple 类中超级sayName() 并使console.log(foo) 显示值?
  2. 我以为 Traceur 会显示编译后的代码,但事实并非如此。例如,$traceurRuntime.createClass() 并没有帮助我了解它是如何创建这些构造函数的。我是否错误地使用 traceur 来查看编译后的代码?

【问题讨论】:

  • "我以为 traceur 会显示编译后的代码,但事实并非如此。",你应该看看6to5.org
  • 您只能在构造函数中使用普通的super()。您需要明确引用要调用的父方法。

标签: javascript ecmascript-6 ecmascript-harmony traceur


【解决方案1】:

super 指的是类/构造函数,而不是调用它的方法。因此,如果你想从sayName() 中调用父函数,你必须这样写:

sayName() {
    var foo = super.sayName();
    console.log(foo);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多