Javascript函数调用:常规调用vs调用与绑定调用 [英] Javascript Function Calls: Regular call vs Call vs Bind Call

查看:94
本文介绍了Javascript函数调用:常规调用vs调用与绑定调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单:
我将一个函数传递给其他函数以便稍后调用(示例回调函数),问题是何时,为什么以及最佳做法是什么。

My question is simple: I'm passing a function to some other function to be call later (sample callback function), the question is when, why and what is the best practice to do it.

示例:
我有 xxx()功能,我必须通过它,正如我在窗口中显示的那样。 onload event。

Sample: I have the xxx() function, and I have to pass it, as I show you below in the window.onload event.

最佳做法是什么?为什么?有任何性能方面或为什么我应该选择使用call或bind来调用此函数

What is the best practice and why? There is any performance aspect or why should I choose to use call or bind to call this function

function xxx(text)
{
    var div = document.createElement("div");
    div.innerHTML = text + " - this: " + this.toString();

    document.body.appendChild(div)
}

function callFunction(func)
{
    func("callFunction");
}

function callUsingCall(func)
{
    func.call(this, ["callUsingCall"]);
}

function callUsingBind(func)
{
    func.call(this, ["callUsingCall"]);
}


window.onload = function(){
    callFunction(xxx);

    callUsingCall(xxx);

    callUsingBind(xxx.bind(document));
}

谢谢,

Sebastian P。

Sebastian P.

推荐答案

我认为没有最佳做法。

你使用调用如果你正在调用的函数关心这个是什么。

You use call if the function you're calling cares what this is.

如果你想确保只用 调用该函数,你可以使用 bind 指定值

You use bind if you want to ensure that the function can only be called with the specified value of this.

[两者都有一些开销,即至少一个函数调用深度/范围]

[There's some overhead to both, i.e. at least one depth of function calls / scope]

否则你只需调用函数。

简单:)

这篇关于Javascript函数调用:常规调用vs调用与绑定调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆