采用一个接受 3 个参数的简单匿名函数:
function hello(firstname, surname, city) {
console.log('Hi ' + firstname + ' ' +
surname + '. I see you\'re from ' + city)
}
使用函数方法“call”调用这个函数比只调用函数有什么好处?,即。
hello('Jane','Mansfield','Philadelphia');
对比
hello.call(this,'Jane','Mansfield','Philadelphia');
fiddle :http://jsfiddle.net/wC3xz/1/
抱歉,查看文档没有发现任何问题。我唯一能想到的是,您是否可以访问传递给函数的 this 对象。但是,在匿名函数(即窗口)的上下文中,从匿名函数内部访问 this 不会是 this 吗?
什么时候需要调用而不仅仅是 functionname(args)?
最佳答案
那么通话有什么大不了的呢?
电话是defined in the spec在第 15.3.4.4 节中。您使用 .call
当您尝试在函数内设置 thisArg 时。
Ito 将如何使用它?
这是如何使用它的示例:
var me = { name: 'dr.eval' }
foo.call(me); // if you omitted the 'call' it would error because this defaults to the window object.
function foo() {
alert(this.name + ' is home');
}
您可以在这里阅读更多相关信息:Function.prototype.call
我什么时候使用它?
这是使用调用时的一个非常典型的例子:
许多 DOM 方法返回 NodeList
。虽然 NodeList 是一个 array-like object ,您不能在其上原生调用数组方法。但是,由于它们在设计上类似于数组,因此您可以使用 .call
如果你打开控制台并输入
document.getElementsByTagName("a").forEach
你会得到未定义的,因为它返回一个没有 forEach 方法的 NodeList。但是,迭代 NodeList 可能是可取的,因此您可以执行以下操作:
[].forEach.call(document.getElementsByTagName("a"),function(elem){
console.log(elem);
});
这将记录页面上的所有 anchor 元素。
另一个常见的例子是 arguments
,它是另一个“Array Like”对象。通常,我们想像处理数组一样处理参数,但我们做不到。再次,.call
来救援,我们可以这样做:
[].slice.call(arguments,0); // returns a clone of arguments, but a real array we can work with!
它在处理事件时也很有用,通常它显示了 JavaScript 的灵 active 。这是一种在对象之间共享功能的方法,否则无法共享它。
关于javascript - 需要在函数对象上调用 JavaScript 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717813/