0

I want to do the following:

someProperty = myFunction().someFunction().someOtherFunction()

howver the last part is called a lot of times, in different sub classes so I made it like so:

class:

class Wheelies {
property0 = someFunction().someOtherFunction()

}

And I want to call getWheels in a sub class, like so, however this does not work:

class Car extends Wheelies {
property1 = myFunction().this.getwheels
}

Can you please guys help me, my question is that I don't know why doesn't it work neither do I know how should I do it.

Peter Toth
  • 678
  • 6
  • 23
  • 1
    There is a nice explanaion in here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes, but basically you would need to return (this) so you can chain the function calls. – JS Lover Feb 11 '20 at 09:42
  • You are probably looking for polymorphic `this`, but your is not complete.. could you provide a minimal example that reproduces what you are trying to do – Titian Cernicova-Dragomir Feb 11 '20 at 09:42
  • Your question is a bit unclear, what exactly are you trying to achieve with your code? – Kokodoko Feb 11 '20 at 09:43
  • 1
    access like this -> property1 = this.property0.this.getwheels; – R0b1n Feb 11 '20 at 09:43
  • `property1 = myFunction()[this.property0]` or `property1 = myFunction()[this.getwheels]` if you have a getter for `property0`. is this what you wanted? – AZ_ Feb 11 '20 at 09:45
  • Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – AZ_ Feb 11 '20 at 09:48
  • Sorry guys if I've been unclear, I'm really just shooting shite at a wall and trying to see what sticks, thanks for all the comments, I've found and marked an answer that worked! – Peter Toth Feb 11 '20 at 15:14

1 Answers1

1

There is a nice explanaion in here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

but basically you would need to return (this) so you can chain the function calls.

class Wheelies {
    constructor(property1) {
        this.property1 = property1;
    }

    someFunction() {
    this.property1 = this.property1 + 'x'
    return this
    }

    someOtherFunction() {
    this.property1 = this.property1 + 'y'
    return this
    }
}


class Car extends Wheelies {
    // this inherits from Wheelies
}


const myCar = new Car("MyCar") 
console.log(myCar.property1) //"MyCar"
console.log(myCar.someFunction().property1) // "MyCarx"
console.log(myCar.someFunction().someOtherFunction().property1) // "MyCarxxy"

You can also change the order of the function calls to produce different results.

JS Lover
  • 622
  • 5
  • 16