采用一个简单的匿名函数,它接受3个参数:
function hello(firstname, surname, city) {
console.log('Hi ' + firstname + ' ' +
surname + '. I see you\'re from ' + city)
}
Run Code Online (Sandbox Code Playgroud)
使用函数方法"call"调用此函数有什么好处,只需调用函数?,即.
hello('Jane','Mansfield','Philadelphia');
Run Code Online (Sandbox Code Playgroud)
VS
hello.call(this,'Jane','Mansfield','Philadelphia');
Run Code Online (Sandbox Code Playgroud)
Fiddle-dee-dee:http://jsfiddle.net/wC3xz/1/
对不起,但是查看文档并没有任何消息.我唯一能想到的是你是否可以访问传递给函数的this对象.但是不会从匿名函数中访问这个在匿名函数即窗口的上下文中吗?
何时需要调用而不仅仅是functionname(args)?
小智 10
呼叫在第15.3.4.4节的规范中定义..call当您尝试在函数内部设置thisArg时使用.
以下是如何使用它的示例:
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');
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里阅读更多相关信息:Function.prototype.call
这是使用调用时非常规范的示例:
很多DOM方法都会返回NodeList.虽然NodeList是一个类似于数组的对象,但您无法在其上本地调用数组方法.但是,由于它们在设计上类似于数组,因此可以使用它们使用数组方法.call
如果您打开控制台并键入
document.getElementsByTagName("a").forEach
Run Code Online (Sandbox Code Playgroud)
你会得到未定义的,因为它返回一个NodeList,它没有forEach方法.但是,可能需要迭代NodeList,因此您可以执行以下操作:
[].forEach.call(document.getElementsByTagName("a"),function(elem){
console.log(elem);
});
Run Code Online (Sandbox Code Playgroud)
这将记录页面上的所有锚元素.
另一个常见的例子是arguments另一个"Array Like"对象.通常,我们希望像数组一样处理参数,但我们不能.再次,.call来救援,我们可以做:
[].slice.call(arguments,0); // returns a clone of arguments, but a real array we can work with!
Run Code Online (Sandbox Code Playgroud)
它在处理事件时也很有用,一般来说它显示了JavaScript的灵活性.这是一种在对象之间共享功能的方法,否则将无法共享它.