问题
I understand that classes in ES6 are really syntactic sugar. Is the super() call really just calling proto? (Is it mapped to the [[prototype]] object?)
回答1:
It's a bit more than that. It also remembers where the method was defined.
const example = {
method() {
return super.method();
}
}
is syntactic sugar for
const example = {
method() {
return Object.getPrototypeOf(example).method.call(this);
}
}
and
class Example {
method() {
return super.method();
}
}
is syntactic sugar for
class Example {
method() {
return Object.getPrototypeOf(Example.prototype).method.call(this);
}
}
As for super()
calls in constructors, it similarly uses Object.getPrototypeOf
on the constructor, but does a bit more there.
Is it mapped to the [[prototype]] object?
Yes. Not to the [[prototype]] of the object that the function was called on (this
), but to the [[prototype]] of the object that the function was defined in.
来源:https://stackoverflow.com/questions/49822056/does-super-map-to-proto-under-the-hood