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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With