Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - Accessing a class field on a superclass

I have a file with the following code:

class Animal {
    doSomething = () => {
        return 'Hi.';
    };
}

class Dog extends Animal {
    doSomething = () => {
        return super.doSomething() + ' Woof!';
    };
}

console.log(new Dog().doSomething());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why is this happening? I am guessing that super can't be used to access a class field

Yes. Class fields are instance properties, but super tries to access properties on the superclass' prototype object. Your Animal class simply doesn't have a doSomething method - instead, every Animal object has a property that contains a bound function.

but what am I supposed to do about this? If I change it to a traditional method, it works

Yes, you are supposed to do exactly that. This is how methods and super work.

Avoid arrow functions when you don't need them, and especially when they don't work. Also have a look at Arrow Functions in Class Properties Might Not Be As Great As We Think.

Is there any way to access a class field of a superclass?

Yes - it is an instance property, and you can access it in your constructor before overwriting it:

class Animal {
    constructor() {
        this.doSomething = () => {
             return 'Hi.';
        };
    }
}

class Dog extends Animal {
    constructor() {
        super();
        const superDoSomething = this.doSomething;
        this.doSomething = () => {
            return superDoSomething() + ' Woof!';
        };
    }
}

Alternatively, with the class fields proposal and no explicit constructor:

class Animal {
    doSomething = () => {
        return 'Hi.';
    }
}

class Dog extends Animal {
    doSomething = (superDoSomething => () => {
        return superDoSomething() + ' Woof!';
    })(this.doSomething)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...