【问题标题】:What is the nodejs equivalent of PHP trait什么是 PHP trait 的 nodejs 等价物
【发布时间】:2018-10-24 22:01:47
【问题描述】:

在 PHP 中,我之前使用过特征,这是一种分离可重用代码的好方法,通常使事情更具可读性。

这是一个具体的例子:(特征和类可以在不同的文件中)。我怎么能在 nodejs 中做到这一点?

<?php

trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
    ..more functions..
}

class TheWorld {
    use HelloWorld;
}

$o = new TheWorldIsNotEnough();
$o->sayHello();

?>

在 Nodejs 中,我看过 Stampit,它看起来很流行,但肯定有一种简单的方法可以在一个不错的 OOP 中组合函数并在不依赖包的情况下在 nodejs 中提高可读性?

感谢您的宝贵时间!

【问题讨论】:

  • 这个问题不够狭窄,不足以成为 Stack Overflow 的主题。这里的想法是使用特定代码帮助解决特定问题,而不是就更广泛的方法问题提供一般性建议或推荐库,因为这些事情往往比其他任何事情都更基于意见。
  • 谢谢@Tomalak。我已经编辑并给出了一个具体的例子。
  • 您在这里展示的内容可以很容易地通过 JS 的原型继承来实现。创建一个拥有你想要的所有方法的对象,使该对象成为另一个对象的原型,另一个对象将获得所有这些方法。在网站 (example) 和其他地方 (如 MDN) 有许多解释原型继承的帖子。我鼓励您阅读该主题。

标签: javascript php node.js


【解决方案1】:

在 JavaScript 中,您可以使用任何函数作为 trait 方法

function sayHello() {
  console.log("Hello " + this.me + "!");
}

class TheWorld {
  constructor() {
    this.me = 'world';
  }
}

TheWorld.prototype.sayHello = sayHello;
var o = new TheWorld();
o.sayHello();

或纯原型版本

//trait
function sayHello() {
  console.log("Hello " + this.me + "!");
}

function TheWorld() {
  this.me = "world";
}

TheWorld.prototype.sayHello = sayHello;
var o = new TheWorld();
o.sayHello();

您甚至可以创建将特征应用于类的函数

//trait object
var trait = {
  sayHello: function () {
    console.log("Hello " + this.me + "!");
  },
  sayBye: function () {
    console.log("Bye " + this.me + "!");
  }
};

function applyTrait(destClass, trait) {
  Object.keys(trait).forEach(function (name) {
    destClass.prototype[name] = trait[name];
  });
}

function TheWorld() {
  this.me = "world";
}

applyTrait(TheWorld, trait);
// or simply
Object.assign(TheWorld.prototype, trait);
var o = new TheWorld();
o.sayHello();
o.sayBye();

【讨论】:

  • 谢谢!我发现了 object.assign()。适用于这种场景?
  • 是的,您可以使用Object.assign(Some.prototype, traitObject)。我创建了单独的函数,因此您可以在此过程中添加一些逻辑
【解决方案2】:

有NPM模块:https://www.npmjs.com/package/traits.js

自述文件中的代码示例:

var EnumerableTrait = Trait({
  each: Trait.required, // should be provided by the composite
  map: function(fun) { var r = []; this.each(function (e) { r.push(fun(e)); }); return r; },
  inject: function(init, accum) { var r = init; this.each(function (e) { r = accum(r,e); }); return r; },
  ...
});

function Range(from, to) {
  return Trait.create(
    Object.prototype,
    Trait.compose(
      EnumerableTrait,
      Trait({
        each: function(fun) { for (var i = from; i < to; i++) { fun(i); } }
      })));
}

var r = Range(0,5);
r.inject(0,function(a,b){return a+b;}); // 10

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2020-12-08
    • 2010-09-23
    • 2017-12-22
    • 2021-11-29
    相关资源
    最近更新 更多