想象一下你有这门课
class Dog{
eat(dogName){
...
}
}然后创建对象并调用and函数。
let doggy = new Dog();
doggy.eat('Max');我如何嵌套牙线功能,例如在吃的函数内,这样我就可以在吃完之后调用这个函数。
let doggy = new Dog();
doggy.eat('Max').floss();我希望对floss函数的调用是可选的,所以只要需要,我就可以调用牙线。
如果我在eat函数中返回这个,我仍然需要在牙线函数中添加狗的名字,这不是我想要的。
doggy.eat('Max').floss('Max');我希望eat函数调用floss函数,并传递狗的名称变量,而不必在floss函数中显式地写入它。
发布于 2022-09-02 09:59:43
因为这似乎是个不确定的问题。
您将“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();https://stackoverflow.com/questions/73580777
复制相似问题