gpt4 book ai didi

javascript - JS : Running methods from the constructor and not using object again

转载 作者:行者123 更新时间:2023-12-03 00:42:13 26 4
gpt4 key购买 nike

我正在编写一个小型 JS 应用程序,想询问一些最佳实践。所以,假设我有一个名为 Dog 的类,如下所示:

class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log(`Bark Bark - ${this.name}`);
}
sayName() {
console.log(`My name is ${this.name}`);
}
}

当我创建一个作为 Dog 类实例的新对象时,我总是需要调用 bark()sayName()。执行此操作时,建议从构造函数中调用这些方法,如下所示:

constructor(name) {
this.name = name;
this.bark();
this.sayName();
}

还是在初始化对象后在外部调用它们更好,如下所示:

let germanShepard = new Dog("german shepard");
germanShepard.bark();
germanShepard.sayName();

注意:执行此操作后,我再也不需要使用 bark()sayName() 了。这只是一次性的事情。

那么,大家有什么推荐的吗?其中一种相对于另一种有什么优势吗?提前致谢。

最佳答案

Is it advised to call these methods from the constructor

不,不要这样做。构造函数应该只初始化一个对象,它不应该做任何其他事情。 (它可能使用辅助方法来做到这一点)。它绝对不应该导致输出或其他副作用。仅使用 new 调用来运行过程,然后丢弃对象是一种反模式。

我建议改为引入静态方法:

class Dog {


static fastLife(name) {
const dog = new this(name);
dog.bark();
dog.sayName();
// dog dies
}
}

Dog.fastLife("german shepard");

… and not using object again

极端地说,为什么你需要一个?当你几乎不使用一个物体时,为什么你还需要它呢?当您需要的只是一个小功能时,不要选择 OOP。

function fastLivedDog(name) {
function bark() {
console.log(`Bark Bark - ${name}`);
}
function sayName() {
console.log(`My name is ${name}`);
}
// in this example, the local functions are called only once
// and could be trivially inlined…
bark();
sayName();
}

fastLivedDog("german shepard");

关于javascript - JS : Running methods from the constructor and not using object again,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53401364/

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