Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the nodejs equivalent of PHP trait

In PHP , I've used traits before which is a nice way of separating out reusable code & generally making things more readable.

Here is a specific Example: ( trait and class can be in separate files ) . How could I do this in nodejs?

<?php

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

class TheWorld {
    use HelloWorld;
}

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

?>

In Nodejs , I have looked at at Stampit which looks quite popular , but surely there is a simple way to compose functions in a nice OOP & make more readable in nodejs without depending on a package?

Thanks for your time!

like image 931
Martin Thompson Avatar asked Jan 02 '23 09:01

Martin Thompson


1 Answers

In JavaScript you can use any function as trait method

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

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

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

or pure prototype version

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

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

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

You can even create function that's apply traits to class

//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();
like image 173
ponury-kostek Avatar answered Jan 04 '23 23:01

ponury-kostek