【问题标题】:Accessing ES6 super properties访问 ES6 超属性
【发布时间】:2016-04-03 16:37:50
【问题描述】:

所以当我看到一些令人惊讶的东西时,我正在乱搞 ES6 类:

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak(sound) {
        console.log(sound);
    }
}

class Dog extends Animal {
    constructor(name, age) {
        super(name);
        this.age = age;
    }
    speak() {
        super.speak("Woof! I'm " + super.name + " and am " + this.age);
    }
}

然后,我创造了我的狗:

var mydog = new Dog("mydog",3);
mydog.speak();

现在打印出来了

Woof! I'm undefined and am 3

所以我的问题是,为什么 super.name 未定义?在这种情况下,我希望它是 mydog

【问题讨论】:

  • super 只能用于访问原型上的属性。使用 this.name 您正在分配给 instance,因此始终需要使用 this 访问它
  • 为什么不能访问 super 属性而是赋值?类 { 名称 = '杰克';说话() { console.log(this.name); } } 类 b 扩展一个 { count() { super.name = 'Lucy'; super.speak(); } } 新 b().count(); // 露西

标签: javascript class inheritance ecmascript-6 super


【解决方案1】:

父构造函数中的this 仍然指代狗,因此this.name = name 直接在Dog 对象上而不是在其父对象上设置属性name。使用this.name 将起作用:

super.speak("Woof! I'm " + this.name + " and am " + this.age);

【讨论】:

  • 嗯,我不想复制属性,不过我需要等待 3 分钟才能接受这个答案
  • 它不会真正被复制,它只会在 Dog 本身上创建。如果您查看您的狗的原型链,您会看到:Dog { name: 'mydog', age: 3 } <- Dog {} <- Animal {} <- {}
猜你喜欢
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 2018-06-16
  • 2017-03-04
相关资源
最近更新 更多