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?

5
  • Possible duplicate of Why are ES6 classes not hoisted? Commented Sep 28, 2017 at 16:37
  • Because it's not a function, but rather a method, and calling it without this. is invalid anyway? Commented Sep 28, 2017 at 16:37
  • 2
    @imcvampire That's a different question. Commented Sep 28, 2017 at 16:37
  • possible duplicate of Javascript: Do I need to put this.var for every variable in an object? Commented Sep 28, 2017 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. Commented Sep 28, 2017 at 16:46

1 Answer 1

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())

Sign up to request clarification or add additional context in comments.

1 Comment

Similarly, f1 = function () {}; is not hoisted, while function f1 () {}; is hoisted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.