Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

闭包其实就是一个结构体 #1

Open
juzi5201314 opened this issue Nov 6, 2021 · 1 comment
Open

闭包其实就是一个结构体 #1

juzi5201314 opened this issue Nov 6, 2021 · 1 comment
Labels
enhancement New feature or request

Comments

@juzi5201314
Copy link

看到了这个
其实闭包可以用结构体来模拟,很多语言也是怎么做的,比如如下闭包:

let a = () => 1 + 2;
print(a());

展开为:

class A {
  function call() {
    return 1 + 2;
  }
}

let a = new A;
print(a.call());

那么如果要捕获作用域里的变量呢?

let cat = 114513;
let a = () => 1 + cat;
print(a());

展开为:

class A {
  var _cat;

  A(cat) {
    this._cat = cat
  }

  function call() {
    return 1 + this._cat;
  }
}

let cat = 114513;
let a = new A(cat);
print(a.call());

相信已经懂了吧,要传入参数也是一样。

@juzi5201314 juzi5201314 added the enhancement New feature or request label Nov 6, 2021
@BottleSome
Copy link

tql橘子

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants