Skip to content

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

@juzi5201314

Description

@juzi5201314

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

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions