javascript - 扩展自容器功能 Javascript

标签 javascript ecmascript-6

考虑以下示例:

var FunctionName = () => {
  return {
    helloWorld() { console.log("hello world"); }
  }
};

var OtherFunctionName = () => {
  return {
    goodBye() { console.log("Bye Bye"); }
  }
};

假设我在上面没有做语法错误的事情,我如何在 OtherFunctionName 中扩展 FunctionName 以便 OtherFunctionName 能够访问helloWorld ??

因为代码库可能包含 ES6 类,是否可以使用相同的方法将所述类扩展为自包含函数以访问类方法?

所以:

var FunctionName = () => {
  return {
    helloWorld() { console.log("hello world"); }
  }
};

class OtherClass {
  goodBye() { console.log("Bye Bye"); }
};

在这种情况下,FunctionName 将扩展 OtherClass 以访问 goodBye可能吗

有哪些方法可以在自包含函数上扩展自包含函数。

在自包含函数上扩展类的方法有哪些

这是 Object.assign 或 lodashes ._extend 派上用场的地方吗?

最佳答案

如果您想使用原型(prototype),可以使用Object.create。 它允许您创建具有特定原型(prototype)的对象。 因为您不想将所有内容更改为“属性描述符”,所以可以将其与 Object.assign 结合使用:

var FunctionName = () => {
  return Object.assign(Object.create(OtherClass.prototype), {
    helloWorld() { console.log("hello world"); }
  })
};

如果您想支持工厂函数和类,可以这样做:

var FunctionName = () => {
  return Object.assign(
    OtherClass.prototype ? Object.create(OtherClass.prototype) : OtherClass(), {
    helloWorld() { console.log("hello world"); }
  })
};

关于javascript - 扩展自容器功能 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37122330/

相关文章:

javascript - 如何创建自定义元素扩展类的新实例

javascript - 如何为传播运算符创建 polyfill

javascript - 使用 MongoDB,如何使用变量中的对象更新数组中的对象?

javascript - 使用 Flot 绘制事件持续时间图表

javascript - 单击菜单以外的任何地方时隐藏菜单

javascript - 如何在WordPress中实现自定义逻辑?

javascript - 在chartjs中查找图表线之间的交点

javascript - Es6 : Short version for destructuring

javascript - 这个功能可以修改一下以提高效率吗?内存和时间

javascript - React/ES6 减少对象