【发布时间】:2020-08-18 19:44:50
【问题描述】:
我知道通过调用 apply 您可以从函数中访问不同的 this 属性,但在这种特定情况下,我不知道为什么它们会有所不同。无论如何,'this'不会来自同一个地方(项目)吗?
这个原始代码不起作用:
_.invoke = function (collection, methodName) {
var slicedArgs = Array.prototype.slice.call(arguments, 2);
return _.map(collection, (item) => {
if (typeof methodName === "string") {
return item[methodName](slicedArgs);
} else {
return methodName.apply(item, slicedArgs);
}
});
};
当我更改地图函数内部的内容时,它运行良好:
_.invoke = function (collection, methodName) {
var slicedArgs = Array.prototype.slice.call(arguments, 2);
return _.map(collection, (item) => {
if (typeof methodName === "string") {
return item[methodName].apply(item, slicedArgs);
} else {
return methodName.apply(item, slicedArgs);
}
});
};
那么与 apply 有什么关系呢?我的第一个代码中的“this”绑定是什么,第二个代码发生了什么变化?
【问题讨论】:
-
第一个是
method([1,2,3]),apply把数组展开到每个参数位置,变成method(1,2,3)。 -
哇,我不敢相信我花了这么长时间。谢谢你,安迪,你让我的大脑免于爆炸!
标签: javascript function underscore.js apply