(0, function)(param)的用法及原理

236 阅读1分钟

今天看了一下webpack打包后的代码,发现有个很奇怪的函数用法:

(0,_add__WEBPACK_IMPORTED_MODULE_0__["default"])(1, 2);

不理解为什么这么写,在网上搜了一下,说是可以改变this指向。

于是我就自己写了个小demo实验了一下:

const obj = {
    test(a) {
        console.log('args: ', a);
        console.log('this: ', this);
    }
};
(0, obj.test)(1);

Chrome浏览器环境下输出:

args:  1
this:  Window {window: Window, self: Window, document: document, name: '', location: Location, …}

node环境下输出:

args:  1
this:  Object [global] { ... }

根据输出结果可以看出,确实改变了this指向,使this指向全局对象Window(浏览器)/global(node)。

原理:

这个特殊的表达式其实是使用了

js 逗号操作符:对它的每个操作数求值(从左到右),并返回最后一个操作数的值。

所以

(0, obj.test)(1);

经过逗号操作符处理后,实际上是:

(function(a) {
    console.log('args: ', a);
    console.log('this: ', this);
})(1);

这样this自然就指向了全局对象。