logo

Scope (1) - "这"是啥

Last Updated: 2023-02-23

放弃?

设全局变量的时候xthis.x是一样的

> x = 10
10
> this.x
10
> this.x = 1
1
> x
1

我们创建一个module如下

> module = { x: 100, getX: function() { return this.x; } }
{ x: 100, getX: [Function: getX] }
> module.getX();
100

然后创建getX2()函数让它和module.getX()相同

> getX2 = module.getX;
[Function: getX]

但结果却完全不同:

> getX2();
1

进阶!

getX2()虽然和module.getX()一样,但其中的this却代表的是全局。

为了保证他们有同样的 scope,可以使用bind(),这样this将被设为第一个参数的 scope。

> getX3 = getX2.bind(module);
[Function: bound getX]
> getX3();
100