Home > database >  Instance returning undefined (JS)
Instance returning undefined (JS)

Time:08-18

I am currently learning JavaScript from MDN and have run into a weird issue that I can't quite figure out. When I type newSquare.sideLength, it returns undefined, despite the instance having a number passed through it. What I need is for it to return the number 4 like I have passed through when creating the instance.

I've tried the same thing with a previous class and it worked perfectly fine but I don't quite understand what is wrong here.

Here's my code:

// OOJS 1
class Shape {
    name;
    sides;
    sideLength;
    constructor(name, sides, sideLength) {
        this.name = name;
        this.sides = sides;
        this.sideLength = sideLength;
    }

    calcPerimeter() {
        console.log(this.sides * this.sideLength);
    }
}

class Square extends Shape {
    constructor(sideLength) {
        super(sideLength);
        this.name = 'Square';
        this.sides = 4;
    }

    calcArea() {
        console.log(Math.pow(this.sideLength, 2));
    }
}

const newSquare = new Square(4);
console.log(newSquare.sideLength);

p.s. Sorry if this has a really simple solution, I've hit a block and I'm really trying to figure it out.

CodePudding user response:

Construction is just like another function and sequence of arguments should be same. when you pass super(sideLength); It sets name = 4 and other two arguments sets to undefined

You have to pass correct sequence of parameters in super function

super('Square', 4, sideLength);

CodePudding user response:

The Shape Class constructor, receive 3 properties, but in the square class, you only call the super constructor with 1 parameter, in this case, the name. So when you call newSquare.sideLength this property has not been initialized and its value is undefined. In Javascript, you need to respect the order of parameters in a constructor or function.

  • Related