gpt4 book ai didi

javascript - 存在继承问题且 Traceur 未显示编译代码的 ES6 类

转载 作者:行者123 更新时间:2023-12-03 11:10:27 25 4
gpt4 key购买 nike

我正在尝试使用 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 类中 super sayName() 并使 console.log(foo) 显示该值?
  2. 我以为 Traceur 会向我显示编译后的代码,但事实并非如此。例如,$traceurRuntime.createClass() 并不能帮助我了解它是如何创建这些构造函数的。我是否错误地使用了traceur来查看编译后的代码?

最佳答案

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

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

关于javascript - 存在继承问题且 Traceur 未显示编译代码的 ES6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com