为什么类内的javascript函数没有被吊起? [英] Why are javascript functions within classes not hoisted?

查看:26
本文介绍了为什么类内的javascript函数没有被吊起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {
  f1() {
    f2();
  }
  f2() {}
}

var a = new A();

console.log(a.f1());

未定义返回f2.

位置:

{
  function f1() {
    return f2();
  }
  function f2() {
    return 'f2';
  }

  console.log(f1());
}

打印'f2'

我只是想知道为什么类中的函数没有被悬挂?

I'm just wondering why functions within classes are not hoisted?

推荐答案

class A {
  f1() {
    return f2()
  }
  f2() {
    return 'f2'
  }
}

var a = new A()

console.log(a.f1())

不等同于

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

以这种形式,应该更清楚为什么引用 f2 失败:范围内没有 f2 函数.由于功能是在原型上设置的,因此您需要使用 this :

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

这篇关于为什么类内的javascript函数没有被吊起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆