什么是与PHP特征相当的nodejs

Mar*_*son 2 javascript php node.js

在PHP中,我使用的特征,其之前是分离出可重用的代码与通常使事情更易读的一个很好的方式.

这是一个具体的例子:(特征和类可以在单独的文件中).我怎么能在nodejs中这样做?

<?php

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

class TheWorld {
    use HelloWorld;
}

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

?>
Run Code Online (Sandbox Code Playgroud)

在Nodejs中,我看过看起来非常流行的Stampit,但是肯定有一种简单的方法可以在一个漂亮的OOP中编写函数并在nodejs中使其更具可读性而不依赖于包?

谢谢你的时间!

pon*_*tek 6

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

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

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

TheWorld.prototype.sayHello = sayHello;
var o = new TheWorld();
o.sayHello();
Run Code Online (Sandbox Code Playgroud)

或纯原型版

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

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

TheWorld.prototype.sayHello = sayHello;
var o = new TheWorld();
o.sayHello();
Run Code Online (Sandbox Code Playgroud)

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

//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();
Run Code Online (Sandbox Code Playgroud)