gpt4 book ai didi

javascript - JS 对象继承与属性

转载 作者:行者123 更新时间:2023-12-02 14:17:25 26 4
gpt4 key购买 nike

我试图为我的项目获得一个非常简单的继承模式,从基类扩展到专门的类。但是,我的专业类的属性正在被父类的属性覆盖。

这是为什么?我该如何解决?

谢谢

function Ship(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 0;
}

function Corvette(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 100;
Ship.call(this, className, x, y)
}


Corvette.prototype = Object.create(Ship.prototype);

var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);

console.log(Corvette.className) // "Smallish" - correct via parameter.
console.log(Corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(Corvette.constructor.name) // Ship

最佳答案

为什么对象中的属性与对象中已有的属性相同?

我建议你这样做

function Ship(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}

function Corvette(className, x, y, speed = 100) {
Ship.call(this, className, x, y, speed);
}

Corvette.prototype = Object.create(Ship.prototype);
Corvette.prototype.constructor = Corvette;

var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);

console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship

如果您的浏览器支持 ES6 的某些功能,请使用此功能 ES6 classes

class Ship { // And also Ship is an abstractionm so you can use `abstract` keyword with it
constructor(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}
}

class Corvette extends Ship {
constructor(className, x, y, speed = 100) {
super(className, x, y, speed);
}
}

var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);

console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship

关于javascript - JS 对象继承与属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com