Method Chaining in a Javascript Class

纵然是瞬间 提交于 2019-12-23 13:26:14

问题


I am attempting to implement method chaining inside my subclass "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);

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

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.setSize(2);

Ball2.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?


回答1:


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.

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



来源:https://stackoverflow.com/questions/48219415/method-chaining-in-a-javascript-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!