最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing ES6 super properties - Stack Overflow

programmeradmin3浏览0评论

So I was messing around with ES6 classes when I saw something surprising:

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);
    }
}

Then, I created my dog:

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

Now this prints

Woof! I'm undefined and am 3

So my question is, why is super.name undefined? I'm expecting it to be mydog in this case.

So I was messing around with ES6 classes when I saw something surprising:

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);
    }
}

Then, I created my dog:

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

Now this prints

Woof! I'm undefined and am 3

So my question is, why is super.name undefined? I'm expecting it to be mydog in this case.

Share Improve this question asked Dec 29, 2015 at 18:43 DowngoatDowngoat 14.4k7 gold badges47 silver badges72 bronze badges 2
  • 4 super can only be used to access properties on the prototype. Using this.name you are assigning to the instance and so always need to access it using this – CodingIntrigue Commented Dec 29, 2015 at 18:52
  • Why can't you access the super attribute but assign a value? class a { name = 'jack'; speak() { console.log(this.name); } } class b extends a { count() { super.name = 'Lucy'; super.speak(); } } new b().count(); // Lucy – weiya ou Commented May 13, 2021 at 14:27
Add a comment  | 

1 Answer 1

Reset to default 18

this in the parent constructor still refers to the dog, so this.name = name, sets the property name directly on the Dog object and not on its parent. Using this.name will work:

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

评论列表(0)

  1. 暂无评论