Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this is not defined error in javascript class constructor? [duplicate]

I can't get my name parameter in my Employee class ! I don't know why I getting error like this is not undefined ! this is for current object right! I don't how to output my name parameter?

class Person {
    constructor(n, a) {
        var p = this;
        p.n = n;
        p.a = a;
        p.total = 0;
        p.a.map(x => p.total += parseInt(x)); //get total salary     
    }
    firstName() {
        return this.n = "Min Min ";
    }
    displayMsg() {
        return " and My yearly income is " + this.total;
    }
}

class Employee extends Person {
    constructor(name, age) {
        this.name = name;
    }
    lastName() {
        return this.name;
    }
    Show() {
        return "My name is " + super.firstName() + this.lastName() + super.displayMsg();
    }
}
emp = new Employee("David", [123, 456, 754]);
console.log(emp.Show());

Actual Output

Uncaught ReferenceError: this is not defined

Expected Output

My name is Min Min David  and My yearly income is 1333
like image 530
David Jaw Hpan Avatar asked Jun 29 '16 03:06

David Jaw Hpan


1 Answers

You need to call the super() constructor first before you can continue instantiating your class:

class Employee extends Person {
    constructor(name, age) {
        super(name, age);
        this.name = name;
    }

    ...
}

JSBin

like image 179
TimoStaudinger Avatar answered Sep 18 '22 13:09

TimoStaudinger