【前端小技巧】调用函数时候,用下面的方法绕过上下文限制
在阅读deepcopy的源码的时候,发现可以使用此技巧绕过函数调用时上下文限制。
源码为:const valueType = (0, _detector.detectType)(value);
原理解释:
-
const valueType = (0, _detector.detectType)(value);这行代码是使用 JavaScript 的特殊语法来调用_detector.detectType函数并将其结果赋值给valueType变量。 -
(0, _detector.detectType)是一种在调用函数时绕过函数上下文限制的常见技巧。这可以避免在调用函数时出现意外的副作用。 -
假设
_detector.detectType是一个可导入的函数,通过(0, _detector.detectType)这种写法,它被称为“逗号运算”或“序列表达式”。这里的(0, _detector.detectType)表示创建了一个临时的匿名函数并立即调用它,作为整个表达式的结果。 -
然后,将
value参数传递给这个临时匿名函数进行调用,并将返回的结果赋值给valueType变量。
上述写法等价于:const valueType = _detector.detectType.call(null, value);