具有继承问题的ES6类和不显示编译代码的Traceur

时间:2014-12-23 14:47:05

标签: javascript ecmascript-6 ecmascript-harmony traceur

我正在尝试使用ES6。特别是类和继承。在课程Apple中,它会扩展Polygon。我想扩展Polygon的方法sayName()并将其转到console.log。

当我通过traceur运行时,我undefined

获得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();

Traceur:

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. 我如何在sayName()课程中超级Apple并让console.log(foo)显示该值?
  2. 我以为traceur会告诉我编译的代码,但事实并非如此。例如,$traceurRuntime.createClass()并没有帮助我了解它是如何创建这些构造函数的。我是否错误地使用traceur来查看已编译的代码?

1 个答案:

答案 0 :(得分:1)

super指的是类/构造函数,而不是调用它的方法。因此,如果要从sayName()内调用父函数,则必须按如下方式编写它:

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