ES6 类的 Mixin,用 babel 转译 [英] Mixins for ES6 classes, transpiled with babel

查看:27
本文介绍了ES6 类的 Mixin,用 babel 转译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据各种来源(2ality, esdiscuss) 应该能够将 mixins 添加到类中:

According to various sources (2ality, esdiscuss) one should be able to add mixins to classes:

EDIT 发现类方法不可枚举,因此无法工作.编辑了下面的代码,但仍然没有快乐

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

我得到了由 Matt Groening 绘制"但不是正在喝啤酒"我得到一个错误

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:

  1. Object.assign 只复制对象的可枚举属性.但是,类的方法和属性是不可枚举的.
  2. 类的方法和属性未在构造函数中定义.它们是在构造函数的原型上定义的.
  1. Object.assign only copies enumerable properties of an object. However, the methods and properties of a class are non-enumerable.
  2. 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 中按预期工作:演示.

It works as expected in Babel: demo.

这篇关于ES6 类的 Mixin,用 babel 转译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆