gpt4 book ai didi

javascript - 在 ES6 代码中扩展 EcmaScript 5 类

转载 作者:数据小太阳 更新时间:2023-10-29 03:55:42 57 4
gpt4 key购买 nike

我想在新项目中使用 EcmaScript 6(通过 Browserify 和 Babelify),但它依赖于用 ES5 编写的第三方库。问题是在我的项目中创建从库中的子类扩展的子类。

例如:

// Library written in ES5
function Creature(type) {
this.type = type;
}

// my code in ES6

class Fish extends Creature {
constructor(name) {
super("fish");
this.name = name;
}
}

除了没有运行 Creature() 构造函数外,这几乎可以正常工作。我设计了一个解决方法/hack,它首先构造父类的对象,然后向其附加内容:

class Fish extends Creature {
constructor(name) {
super("throw away"); //have to have this or it wont compile
let obj = new Creature("fish");
obj.name = name;
return obj;
}
}

只要原始类没有“构造函数”函数,这种方法似乎就可以工作。

我的问题是:这是在使用 ES6 的类时扩展它们的最佳方式吗(除了要求库的作者迁移之外)?或者有更好的方法吗?我想在我的项目中继续使用 class {} 语法。

最佳答案

您的解决方案使用 babel 可以正常工作。您的代码被编译为以下 ES5 代码。

// Library written in ES5
"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }

function Creature(type) {
this.type = type;
}

// my code in ES6

var Fish = (function (_Creature) {
function Fish(name) {
_classCallCheck(this, Fish);

_Creature.call(this, "fish");
this.name = name;
}

_inherits(Fish, _Creature);

return Fish;
})(Creature);

从上面的代码可以看出,正确调用了Creature类的构造函数。行 _Creature.call(this, "fish");

Babel link

我添加了以下代码来证明 fish 是 Creature 的一个实例,也是 Fish 的一个实例。

var fish = new Fish("test");

console.log(fish.type);
console.log(fish.name);

console.log( fish instanceof Creature );
console.log( fish instanceof Fish);

输出:

fish
test
true
true

关于javascript - 在 ES6 代码中扩展 EcmaScript 5 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30446277/

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