如何正确实现扩展“父”类并从后者继承类字段的“子”类?

问题描述 投票:0回答:3

这是我的任务

  • 实现一个扩展父类的子类。
  • 在Child类中添加一个构造函数就可以调用super()。
  • 在 Child 类中实现一个新函数 addNewAbilities(newAbility) ,新能力将被添加到 Parent 的 #abilities 数组中。

我尝试在此处添加创建新功能,但它不起作用。不确定我是否正确创建了该函数。有谁帮忙看看吗

class Parent {
    abilities = []

    constructor(){
        this.abilities.push("Parenting");
        this.abilities.push("Role modeling");
    }

    showAbilities(){
        console.log("These are the abilities:")
        for(const a of this.abilities){
            console.log(a);
        }
    }
}

const p = new Parent();
p.showAbilities(); // Observe that this function prints "Parenting" and "Role modeling".

// Task 1: Add code here
class Child extends Parent {
    addNewAbility = []

    super() {
        this.addNewAbility.push("Parenting");
    }
}

const c = new Child();
c.addNewAbility("Dancing");
c.showAbilities(); // This function should print "Parenting", "Role modeling" and "Dancing".

javascript class inheritance super es6-class
3个回答
0
投票

您需要在子类的构造函数中调用

super

class Child extends Parent {
    addNewAbility = []
    
    constructor() {
        super()
        this.addNewAbility.push("Parenting")
    }

当您在构造函数中调用

super
时,它会从子类中调用父类的构造函数。

这里有一个链接,很好地解释了

super
的工作原理。


0
投票

Child
类中,您不需要将 'addNewAbility' 定义为数组。相反,您应该使用从
Parent
类继承的能力属性来存储更多能力。

此外,您的

Child
类缺少
constructor
函数。构造函数应该使用
super()
关键字来调用父类
Parent
的构造函数。

这里是您修改后的代码:

class Child extends Parent {
    constructor() {
        super(); 
        this.abilities.push("Childcare"); 
    }
}

干杯!


0
投票

我已经非常仔细地阅读了交给OP的任务的所有要点。

除了同意所提供的课程材料质量较差之外,我还注意到

#
数组的哈希前缀 /
#abilities

第一点和第二点之后...

  • 实现一个
    Child
    类,扩展
    Parent
  • Child 类添加一个
    构造函数
    [...可以调用...]
    super()

...第三点确实针对

Child
类实现...

  • addNewAbilities([...])
    类中实现一个新函数
    Child
    ,新能力将添加到
    Parent
    #abilities
    数组
    中。

尽管这个精确的表述揭示了人们对哪种语言特征与有用的现实世界实现相关的缺乏理解,但该任务是可以解决的。

如果

#abilities
被正确解释为 私有类属性,要知道的最重要的一般原则是……

  • 私有类属性不能被继承

但是我们可以模拟这样一种行为,下一个经过彻底注释的示例代码将证明......

class Parent {
  /*
   *  ... private property ...
   *
   *  - note the hash prefix
   *    as of the given task ...
   *
   *    "... where the new ability will be
   *     added to the Parent's #abilities array"
   */
  #abilities = [];

  constructor(){
    this.#abilities.push('Parenting', 'Role modeling');
  }
  get abilities () {
    // - with a getter one never ever does
    //   directly expose the protected value.

    return [...this.#abilities]; 
  }
}

class Child extends Parent {
  /*
   *  I m p o r t a n t:
   *
   *  - private class properties can not be inherited.
   *
   *  - thus one has to   e m u l a t e
   *    what the given task does ask for ...
   *
   *    "Implement a new function addNewAbilities [...]
   *     in the Child class where the new ability will
   *     be added to the Parent's #abilities array."
   */
  #abilities = [];

  constructor() {
    super();

    // - N o t e:
    //
    //   Both getter calls do access the same reference as long as
    //   `Child` does not implemented its own `abilities` getter.

    console.log('Child::new ... this.abilities ...', this.abilities);
    console.log('Child::new ... super.abilities ...', super.abilities);
  }

  // shadowing the super getter.

  get abilities () {
    // - return a concatenated array of just
    //   unique super and child ability values.

    return [
      ...new Set(
        super.abilities.concat(this.#abilities)
      )
    ];
  }

  addAbilities(...args) {
    // - make sure a child's `abilities`
    //   contains unique values only.

    this.#abilities = [
      ...new Set(
        this.#abilities.concat(args.flat())
      )
    ];
    // - use the child's `abilities` getter in order
    //   to return the correct overall abilities size.

    return this.abilities.length;
  }
}
const parent = new Parent;
const child = new Child;

console.log('parent.abilities ...', parent.abilities);
console.log('child.abilities ...', child.abilities);

console.log('child.addAbilities(...) ...',
  child.addAbilities(
    'Rules challenger', 'Wellspring of Joy',
    'Parenting', 'Role modeling',
    'Rules challenger', 'Wellspring of Joy',
  )
);
// ... same ...

/*console.log('child.addAbilities(...) ...',

  // single array instead of mutiple parameters.
  
  child.addAbilities([
    'Rules challenger', 'Wellspring of Joy',
    'Parenting', 'Role modeling',
    'Rules challenger', 'Wellspring of Joy',
  ])
);*/
console.log('parent.abilities ...', parent.abilities);
console.log('child.abilities ...', child.abilities);
.as-console-wrapper { min-height: 100%!important; top: 0; }

编辑 ...在OP ...

在正常的类字段(公共字段)的情况下,上面的示例代码可以归结为与以下提供的代码一样短的内容...

class Parent {
  constructor() {
    this.abilities = ['Parenting', 'Role modeling'];
  }
  logAbilities() {
    console.log(
      `The ${ this.constructor.name } instance has following abilities ... ${ this.abilities.join(', ') }`
    );
  }
}

class Child extends Parent {
  constructor() {

    super();

    console.log('Child::new ... this.abilities ...', this.abilities);
  }

  addAbilities(...args) {
    // - make sure a child's `abilities`
    //   contains unique values only.

    this.abilities = [
      ...new Set(
        this.abilities.concat(args.flat())
      )
    ];
    return this.abilities.length;
  }
}
const parent = new Parent;
const child = new Child;

console.log('parent.abilities ...', parent.abilities);
console.log('child.abilities ...', child.abilities);

console.log('child.addAbilities(...) ...',
  child.addAbilities(
    'Rules challenger', 'Wellspring of Joy',
    'Parenting', 'Role modeling',
    'Rules challenger', 'Wellspring of Joy',
  )
);
// ... same ...

/*console.log('child.addAbilities(...) ...',

  // single array instead of mutiple parameters.
  
  child.addAbilities([
    'Rules challenger', 'Wellspring of Joy',
    'Parenting', 'Role modeling',
    'Rules challenger', 'Wellspring of Joy',
  ])
);*/
console.log('parent.abilities ...', parent.abilities);
console.log('child.abilities ...', child.abilities);

console.log('\nparent.logAbilities() ...\n\n');
parent.logAbilities();

console.log('\nchild.logAbilities() ...\n\n');
child.logAbilities();
.as-console-wrapper { min-height: 100%!important; top: 0; }

© www.soinside.com 2019 - 2024. All rights reserved.