0

I am experimenting with ES6. In particular, classes and inheritance. In class Apple, it extends Polygon. I want to extend Polygon's method sayName() and have it go to console.log.

When I run it through traceur, I get 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();

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. How can I super sayName() in Apple class and make the console.log(foo) show the value?
  2. I thought traceur would show me the compiled code, but it is not really. For instance, $traceurRuntime.createClass() isn't helping me see how it is creating these constructors. Am I using traceur incorrectly to view the compiled code?
Cœur
  • 32,421
  • 21
  • 173
  • 232
dman
  • 10,780
  • 16
  • 86
  • 174
  • 1
    "I thought traceur would show me the compiled code, but it is not really.", you should take a look at https://6to5.org/ – James Kyle Dec 23 '14 at 15:14
  • You can use a plain `super()` only in constructors. You'll need to explicitly refer to the parent method that you want to call. – Bergi Jan 12 '15 at 11:15

1 Answers1

1

super refers to the class/constructor, not to the method from which it is called. Therefore, if you want to call the parent function from within sayName(), you will have to write it like this:

sayName() {
    var foo = super.sayName();
    console.log(foo);
}
lyschoening
  • 16,412
  • 10
  • 37
  • 50