JS对象的属性继承

JS object inheritance with attributes

本文关键字:属性继承 对象 JS      更新时间:2023-09-26

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

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

谢谢,

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

为什么在child对象中有与parent's中相同的属性?

我建议你这样做

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类

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

您只需要在Corvette功能开始时移动Ship.call(this, className, x, y)

还有,下次,在发布代码之前,检查它是正确的,你写的console.log(Corvette)而不是console.log(corvette)

另一件事:你不需要重复你不想覆盖的参数

function Ship(className, x, y){
    this.className = className;
    this.x = x;
    this.y = y;
    this.speed = 0;
}
function Corvette(className, x, y){
    Ship.call(this, className, x, y)   
    this.speed = 100;        
}
Corvette.prototype = Object.create(Ship.prototype);   
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className)
console.log(corvette.speed)
console.log(corvette.constructor.name)

你应该先调用parentclass构造函数,然后重写属性,这样由Corvette设置的属性不会被父类改变,即:

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