在JS中创建一个可以在同一行中调用另一个函数的函数,就好像它是一个返回值一样



想象一下你有这个类

class Dog{
eat(dogName){
...
}
}

然后创建对象并调用eat函数

let doggy = new Dog();
doggy.eat('Max');

我如何将floss函数嵌套在eat函数中,以便在eat 之后立即调用该函数

let doggy = new Dog();
doggy.eat('Max').floss();

我希望对牙线功能的调用是可选的,这样我就可以在需要的时候调用牙线。

如果我在eat函数中返回这个,我仍然需要在牙线函数中添加狗的名字,这不是我想要的。

doggy.eat('Max').floss('Max');

我希望eat函数调用floss函数并传递dog的name变量,而不必在floss函数中显式写入它。

因为这似乎是一个不稳定的问题。。

您正在传递"Max"作为参数,以定义Dog的属性。

下面的方法不是更合乎逻辑、更面向对象吗?

let doggy = new Dog(); // we have a new Dog
doggy.Name = "Max"; // his name is Max
doggy.eat(); // Max eats.
doggy.eat().floss(); // Max eats and flosses.
doggy.eat('Tom'); // Max eats Tom, the resulting instance of a Dog is still Max.
// This keeps the function pure.

Floss函数示例:

floss(){
let name = this.Name; // 'Max'
}

通过这种方式,您可以"保留"变量,并以干净的方式使其在其他函数中可用;将所述信息存储在所述对象中。


旧答案:

假设eat存在于咀嚼、吞咽和牙线中。这就是你对它的定义:

class Dog{
eat(){
chew(); // calling chew
swallow();
floss();
}
chew(){ // defining chew
}
swallow(){
}
floss(){
}
}

也可以继续返回如下实例:

class Dog{
chew(){ // defining chew
return this;
}
swallow(){
return this;
}
floss(){
return this;
}
}

导致

let doggy = new Dog();
doggy.chew().swallow().floss();

最新更新