Javascript 向作为参数的函数添加参数
我不知道如何恰当地解释这一点,但基本上我有:Javascript 向作为参数的函数添加参数,javascript,Javascript,我不知道如何恰当地解释这一点,但基本上我有: mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, function (data) { that.tempName(data, "osType", cb); }); 我希望它看起来像: mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList
mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, function (data) {
that.tempName(data, "osType", cb);
});
我希望它看起来像:
mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, that.tempName.someExtendingFunction("osType", cb));
我在寻找“someExtendingFunction”,它可以让我做到这一点。这可能吗?没什么大不了的,但会把事情搞清楚的
感谢您在
函数.prototype.bind中使用bind
:
mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, that.tempName.someExtendingFunction.bind(null, "osType", cb));
这只适用于兼容ECMAScript 5的浏览器。如果您想要旧浏览器支持的内容,可以使用下划线.js并使用其\uuwk.bind
功能
mg.postGiApi("Dashboard", "postChartOsTypeData", { groupIdList: that.idList }, _.bind(that.tempName.someExtendingFunction, null, "osType", cb));
这将返回一个函数,该函数将使用传递给它的参数进行调用
null
指该变量的此
您可以在此处阅读有关bind
的更多信息:没有本机函数可以执行此操作,但您可以编写类似的函数:
function someExtendingFunction(context, name, type, cb) {
return function(data) {
context[name].call(context, data, type, cb);
};
}
mg.postGiApi("Dashboard",
"postChartOsTypeData",
{ groupIdList: that.idList },
someExtendingFunction(that, "tempName", "osType", cb));
请注意,that.tempName.someExtendingFunction(…)
永远不会工作,因为that
上下文将丢失。如果将someExtendingFunction
作为方法上的(Function.prototype
)方法调用,则需要显式提供上下文,就像这样。不完全一样<代码>数据
是第一个参数,而不是最后一个参数。您还忘记将该作为上下文传递。使用null
时,它可能无法工作。