gpt4 book ai didi

javascript - 'call' 在 javascript 中如何工作?

转载 作者:可可西里 更新时间:2023-11-01 02:56:51 24 4
gpt4 key购买 nike

我对 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) 时,内部会发生什么?

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

最佳答案

Yehuda Katz 拥有 a good writeup JavaScript 的 Function#call 方法。他的文章应该可以回答您的问题,此外还有许多后续问题。

当您直接调用函数时,使用一般语法:

var foo = function() {
console.log("foo");
return this;
};
foo(); // evaluates to `window`

那么函数调用内部的this就是函数调用外部的this。默认情况下,在浏览器中,任何函数调用之外的 this 都是 window。所以在上面的函数调用中,this 默认也是 window

当您使用方法调用语法调用函数时:

var bar = {
foo: function() {
console.log("foo");
return this;
}
};
bar.foo(); // evaluates to `bar`

那么函数调用中的 this 就是最右边句点左边的对象:在本例中是 bar

我们可以使用 call 来模拟这种情况。

当你在一个对象外设置了一个函数,并且想在设置为一个对象的函数调用中用this调用它,你可以:

var foo = function() {
console.log("foo");
return this;
}
var bar = { };
foo.call(bar); // evaluates to `bar`

您也可以使用此技术来传递参数:

var foo = function(arg1, arg2) {
console.log("foo");
return arg1 + arg2;
}
var bar = { };
foo.call(bar, "abc", "xyz"); // evaluates to `"abcxyz"`

关于javascript - 'call' 在 javascript 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7265587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com