2015-05-25 56 views
5

我想在新项目中使用EcmaScript 6(通过Browserify和Babelify),但它取决于ES5中编写的第三方库。问题是在我的项目中创建子类,这些子类从库中的子类延伸出来。在ES6代码中扩展EcmaScript 5类

E.g:

// 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; 
    } 
} 

这几乎工程,除了生物()构造函数无法运行。我设计了一个解决方法/破解它首先构造父类的对象,然后追加的东西吧:

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 {}语法。

+1

Babel依靠ES5类正确设置'Creature.prototype.constructor = Creature',也许你没有做到这一点?如果父类是绝对基类,那应该自动发生,但是如果父类有它自己的父类,那么可能它有错误的'.constructor'。 – loganfsmyth

回答

2

您的解决方案使用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

添加以下代码以证明鱼的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 
0

ES5构造函数和ES6类可以在继承链无缝住。如果您使用Babel等工具将您的代码在运行前转储到ES5中,您可以看到它全部转换为基于Prototype的继承。请看这个例子here,它有三个级别的继承链中的类和构造函数。希望这可以帮助。