gpt4 book ai didi

javascript - PHP trait 的 nodejs 等价物是什么

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:20 25 4
gpt4 key购买 nike

在 PHP 中,我之前使用过 traits,这是分离可重用代码并通常使代码更具可读性的好方法。

这是一个具体的例子:(特征和类可以在单独的文件中)。我怎么能在 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 中提高可读性?

感谢您的宝贵时间!

最佳答案

在 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();

或纯原型(prototype)版

//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();

关于javascript - PHP trait 的 nodejs 等价物是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50343941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com