'call'如何在javascript中工作? [英] How does 'call' work in javascript?

查看:125
本文介绍了'call'如何在javascript中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有'call'的问题。

I have a question on 'call' in javascript.

var humanWithHand = function(){
    this.raiseHand = function(){
        alert("raise hand");
    }
}

var humanWithFoot = function(){
    this.raiseFoot = function(){
        alert("raise foot");
    }
}

var human = function(){

    humanWithHand.call( this );
    humanWithFoot.call( this );

}

var test = new human();

所以..当我使用'call'作为humanWithHand.call(this)时,内部会发生什么?

so..when I use 'call' as humanWithHand.call(this), what happens internally?

humanWithHand变量将其属性和成员复制(或指向?)到人类变量的原型?

does humanWithHand variable copies (or points?) its properties and members to human variable's prototype?

推荐答案

.call()设置这个值,然后用你传递给 .call()的参数调用该函数。你使用 .call()而不是直接调用函数当你想在被调用的内部设置这个值函数而不是设置为javascript通常设置的任何函数。

.call() sets the this value and then calls the function with the arguments you passed to .call(). You use .call() instead of just calling the function directly when you want to set the this value inside the called function rather than let it be set to whatever javascript would normally set it to.

.apply()是一个妹妹的功能。它还可以设置这个值,它可以接受数组中的参数,以便在尝试从其他函数调用或其他函数调用时传递变量参数列表时使用它。你正在以编程方式构造一个参数列表,根据情况可能会有不同数量的参数。

.apply() is a sister function. It can also set the this value and it can take arguments in an array so it can be used when you are trying to pass a variable argument list from some other function call or when you're constructing an argument list programmatically which may have different numbers of arguments depending upon the situation.

这篇关于'call'如何在javascript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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