TransWikia.com

Is it possible to call class methods from the `contructor` in javascript?

Stack Overflow Asked by Grateful on December 9, 2021

The following is an example of an ES6 Class.

class Car {
    constructor(brand) {
        this.brand = brand;
        // this.setBrand(brand); // how is it possible to do this?
    }
    
    setBrand(brand) {
        this.brand = brand;
    }
    
    getBrand() {
        return this.brand;
    }
    
    getAd() {
        return `${this.brand} is the best brand out there!!`;
    }
}

However, since the constructor is just a repeat of the method setBrand, I was wondering how it would be possible to remove the redundancy and perhaps call setBrand from within the constructor.

Any pointers?

2 Answers

You can call the method by doing:

        class Car {
            constructor(brand) {
                this.setBrand(brand); <--------
            }

            setBrand(brand) {
                this.brand = brand;
            }
        }

in this case it's ok because you are only assigning a value to a property, but keep in mind it's a bad practice to make the constructor do anything other than create the object.

Answered by Joel Imbergamo on December 9, 2021

You can do as you suspect. In the constructor this is a reference to the new object so you can call class methods in it. The code below runs properly.

class Car {
    constructor(brand) {
        this.setBrand(brand); // this works fine
    }
    
    setBrand(brand) {
        this.brand = brand;
    }
    
    getBrand() {
        return this.brand;
    }
    
    getAd() {
        return `${this.brand} is the best brand out there!!`;
    }
}

let car = new Car("DeLorean")
console.log(car.getBrand())
console.log(car.getAd())

Answered by Always Learning on December 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP