2
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?

755
  • 2,991
  • 3
  • 20
  • 34
  • Possible duplicate of [Why are ES6 classes not hoisted?](https://stackoverflow.com/questions/35537619/why-are-es6-classes-not-hoisted) – Quoc-Anh Nguyen Sep 28 '17 at 16:37
  • Because it's not a function, but rather a method, and calling it without `this.` is invalid anyway? – Bergi Sep 28 '17 at 16:37
  • 2
    @imcvampire That's a different question. – Bergi Sep 28 '17 at 16:37
  • possible duplicate of [Javascript: Do I need to put this.var for every variable in an object?](https://stackoverflow.com/q/13418669/1048572?javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) – Bergi Sep 28 '17 at 16:39
  • @Bergi, I don't think that's quite a duplicate either, because it doesn't reference the use case where functions are defined as part of a class. I think the question is a good one because it's easy to confuse the shorthand naming convention with declaring a variable in scope. – zzzzBov Sep 28 '17 at 16:46

1 Answers1

5

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())
zzzzBov
  • 174,988
  • 54
  • 320
  • 367