问题
class A {
f1() {
f2();
}
f2() {}
}
var a = new A();
console.log(a.f1());
returns f2 is not defined.
Whereas:
{
function f1() {
return f2();
}
function f2() {
return 'f2';
}
console.log(f1());
}
prints 'f2'
I'm just wondering why functions within classes are not hoisted?
回答1:
class A {
f1() {
return f2()
}
f2() {
return 'f2'
}
}
var a = new A()
console.log(a.f1())
is not equivalent to
{
function f1() {
return f2()
}
function f2() {
return 'f2'
}
console.log(f1())
}
Instead, it is syntactic sugar for:
function A() {
}
A.prototype.f1 = function () {
return f2()
}
A.prototype.f2 = function () {
return 'f2'
}
var a = new A()
console.log(a.f1())
In this form, it should be more clear why referencing f2
fails: there is no f2
function in scope. Because the functions are set on the prototype, you'll need to access them using this
:
class A {
f1() {
return this.f2()
}
f2() {
return 'f2'
}
}
var a = new A()
console.log(a.f1())
来源:https://stackoverflow.com/questions/46474094/why-are-javascript-functions-within-classes-not-hoisted