4

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?

2
  • setName(name) { this.name = name; } is enough no need ` setBall.setName(name) { this.name = name; }` Commented Jan 12, 2018 at 4:14
  • It's not Javascript It's Typescript so you don't have a prototype. Have you tried to return this at the end of each method? Commented Jan 12, 2018 at 4:18

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, adding "return this" to the end of each method, and removing "setBall." at the beginning, has my methods chaining.
@MJohnston May i ask if this is an efficient design pattern? I love to have classes that have chainable methods and just thought of doing it that way, but what if i have an object that stores a huge amounnt of data, will it not lead to unneccessary memory usage doing it that way? Since each time a method returns itself if replicates? Or is the object just returend as a reference thus not causing additional memory usage?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.