Why are javascript functions within classes not hoisted?

故事扮演 提交于 2021-02-08 07:24:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!