Javascript类中的方法链接 [英] Method Chaining in a Javascript Class

查看:53
本文介绍了Javascript类中的方法链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在子类"setBall"

class Ball {
  constructor(name, size, power) {
    this.name = name;
    this.size = size;
    this.power = power;
  }   
}

let Ball1 = new Ball('Bomb',5,2);
console.log(Ball1);

class setBall extends Ball{
  constructor(name, size, power) {
    super(name, size, power);
  }

  setBall.setName(name) {
    this.name = name;
  }

  setBall.setSize(size) {
    this.size = size;
  }

  setBall.setPower(power) {
    this.power = power;
  }

  get getthrowSpeed() {
    return this.size + this.power;
  }
}

let Ball2 = new setBall('Big',3,7);
console.log(Ball2);

我在控制台中测试它时收到的错误是: 未捕获的SyntaxError:意外的令牌.

The error i recieve when testing it in the console is: Uncaught SyntaxError: Unexpected token .

如果我在它们之间也添加.prototype,则会发生相同的错误.这些方法无需在它们前面使用'setBall.'即可工作,但无需输入:

The same error occurs if I add .prototype in between them as well. The methods work without 'setBall.' in front of them, but instead of inputing:

* Ball2.setName('blue');

*Ball2.setName('blue');

Ball2.setSize(2);

Ball2.setSize(2);

Ball2.setPower(3); *

Ball2.setPower(3);*

我想输入:Ball2.setName('blue').setSize(2).setPower(3);

I would like to input: Ball2.setName('blue').setSize(2).setPower(3);

我的问题是, 如何在类中链接这些方法?

My question is, how do I chain these methods within the class?

推荐答案

如果您要在每个函数的末尾返回ball(在示例Ball2中为例)对象,它将起作用.您可以通过在每个函数的末尾调用"return this"来链接方法来做到这一点.

if you were to return the ball (in the case of your example Ball2) object at the end of each of your functions it will work. you can do this by calling "return this" at the end of each function to chain methods.

您可以看一下Wikipedia Java示例,以了解他们如何实现它: https://en.wikipedia.org/wiki/Method_chaining

you can take a look at the wikipedia java example to see how they implement it: https://en.wikipedia.org/wiki/Method_chaining

这篇关于Javascript类中的方法链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆