用于ES6类的混合物,与巴贝尔一起蒸发 [英] Mixins for ES6 classes, transpiled with babel
本文介绍了用于ES6类的混合物,与巴贝尔一起蒸发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据各种来源( 2ality , esdiscuss )应该能够将mixin添加到类中:
According to various sources (2ality, esdiscuss) one should be able to add mixins to classes:
编辑发现类方法不可枚举,因此无法正常工作。编辑下面的代码,但仍然没有喜悦
EDIT discovered that class methods are not enumerable so that cannot work. Edited the code below, but still no joy
class CartoonCharacter {
constructor(author) {
this.author = author;
}
drawnBy() {
console.log("drawn by", this.author);
}
}
// THIS CANNOT WORK
// class methods are not enumerable
// class Human {
// haveFun() {
// console.log("drinking beer");
// }
// }
let Human = Object.create({}, {
haveFun: {
enumerable: true,
value: function () {
console.log("drinking beer");
}
}
});
class Simpson extends Object.assign(CartoonCharacter, Human) {
constructor(author) {
super(author);
}
}
let homer = new Simpson("Matt Groening");
homer.drawnBy(); // expected: drawn by Matt Groening
homer.haveFun(); // expected: drinking beer
我得到了马特·格林兴所绘,而不是喝酒啤酒我收到错误
I get the "drawn by Matt Groening" but instead of the "drinking beer" I get an error
-> Uncaught TypeError: E.haveFun is not a function
推荐答案
你的mixin有两个问题:
There are two problems with your mixins:
-
Object.assign
只复制对象的枚举属性。但是,类的方法和属性是不可枚举的。 - 类的方法和属性没有在构造函数上定义。它们是在构造函数的原型上定义的。
Object.assign
only copies enumerable properties of an object. However, the methods and properties of a class are non-enumerable.- The methods and properties of a class are not defined on the constructor. They are defined on the prototype of the constructor.
这是你如何使用mixins扩展一个类:
This is how you would extend a class using mixins:
class CartoonCharacter {
constructor(author) {
this.author = author;
}
drawnBy() {
console.log("drawn by", this.author);
}
}
class Human {
haveFun() {
console.log("drinking beer");
}
}
mixin(CartoonCharacter, Human);
class Simpson extends CartoonCharacter {
constructor(author) {
super(author);
}
}
let homer = new Simpson("Matt Groening");
homer.drawnBy(); // expected: drawn by Matt Groening
homer.haveFun(); // expected: drinking beer
function mixin(target, source) {
target = target.prototype; source = source.prototype;
Object.getOwnPropertyNames(source).forEach(function (name) {
if (name !== "constructor") Object.defineProperty(target, name,
Object.getOwnPropertyDescriptor(source, name));
});
}
它按照预期在Babel中工作:demo 。
It works as expected in Babel: demo.
这篇关于用于ES6类的混合物,与巴贝尔一起蒸发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文