【问题标题】:javascript super, additional properties returning undefined [closed]javascript超级,返回未定义的附加属性[关闭]
【发布时间】:2022-01-09 16:13:17
【问题描述】:

我在一门课程中学习继承,但是我在 MDN 上找到了 super 关键字,我开始实现它,它有点工作,它将返回父类中的两个属性,但附加属性 i尝试在子类中实现总是返回未定义,我怎样才能以正确的方式添加属性,因为我开始理解它可能是错误的,超级将 this 关键字应用于父类。这是我的代码...

class Car {
    constructor(speed, make){
        this.speed = speed,
        this.make = make
    }
get speed() {
    return this._speed / 1.6;
}

set speed(mov){
     this._speed = mov * 1.6
}

accel(){
    console.log(this.speed += 5);
}
}

const chevy = new Car(120, 'chevy');

//challenge 3

class Ev extends Car{
    constructor(speed,make,bat){
        super(speed,make)
        this.bat
    }
    billy(){
        console.log('hi');
    }
    chargeBat(charge){
        this.bat = charge;
        return `ur battery is charging to ${charge}`;
    }
    cel(){
        this.speed += 20;
        this.bat - 1;
        return `your car is going ${this.speed} and battery is ${this.bat}`
    }
}
// Ev.protype = Object.create(Car.prototype);

const prius = new Ev(35,'prius',99);
// console.log(prius.chargeBat());
// console.log(prius.cel())
console.log(prius.bat);
console.log(prius.speed)

【问题讨论】:

  • 在构造函数中,你不会对this.batbat 做任何事情。你正在寻找this.bat = bat;,就像你在基类中做的那样。
  • 您没有设置 bat 值。在 Ev ctor 中尝试 this.bat = bat;
  • 同样,您可能指的是this.bat -= 1;,而不是cel 方法中的this.bat - 1;
  • 另外,不要使用逗号运算符来分配多个属性。 this.speed = speed; this.make = make;,而不是 this.speed = speed, this.make = make;。使用JSHint 等工具立即发现代码问题。

标签: javascript inheritance super


【解决方案1】:

您在 Ev 构造函数中丢弃了 bat 值。将其存储在this.bat 中以更正该问题。请参阅下面的代码。

class Car {
    constructor(speed, make){
        this.speed = speed,
        this.make = make
    }
get speed() {
    return this._speed / 1.6;
}

set speed(mov){
     this._speed = mov * 1.6
}

accel(){
    console.log(this.speed += 5);
}
}

const chevy = new Car(120, 'chevy');

//challenge 3

class Ev extends Car{
    constructor(speed,make,bat){
        super(speed,make)
        this.bat = bat;    // <------------- HERE
    }
    billy(){
        console.log('hi');
    }
    chargeBat(charge){
        this.bat = charge;
        return `ur battery is charging to ${charge}`;
    }
    cel(){
        this.speed += 20;
        this.bat - 1;
        return `your car is going ${this.speed} and battery is ${this.bat}`
    }
}
// Ev.protype = Object.create(Car.prototype);

const prius = new Ev(35,'prius',99);
// console.log(prius.chargeBat());
// console.log(prius.cel())
console.log(prius.bat);
console.log(prius.speed)

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多