JavaScript 调用和应用 101
使用调用
使用 apply
如何记住 call 与 apply 参数
资源/更多阅读材料:
如果你花了足够多的时间阅读 JavaScript 代码,你可能见过call
和apply
。如果你像我一样,很快就会感到困惑。别担心,这些方法很容易理解。我会介绍一些基础知识,帮助你入门!
我将回顾一下:
- 如何使用呼叫
- 如何使用应用
- 何时使用 call 以及何时使用 apply
在开始之前,请记住这两者非常相似。学习其中一个可以帮助我们理解另一个。
使用调用
假设我们有一个对象和一个函数:
const breakfastObj = {
food: 'blueberry waffles',
drink: 'orange juice'
}
function sayBreakfast(){
console.log(`I had ${this.food} and ${this.drink} for breakfast`)
}
当我们调用时sayBreakfast()
,它会返回
sayBreakfast() // I had undefined and undefined for breakfast
sayBreakfast()
使用breakfastObj
as 来“调用”该函数this
:
sayBreakfast.call(breakfastObj) // I had blueberry waffles and orange juice for breakfast
回想一下this
,如果没有定义,则指的是全局对象(如果你在浏览器中,你的全局对象很可能就是window
一个对象)。因此我们可以这样做:
window.food = 'French toast'
window.drink = 'Apple juice'
sayBreakfast() // ... French toast and Apple juice
这相当于:
sayBreakfast.call() // ... French toast and Apple juice
Call 还接受第 2、3、...n 个参数。这些参数用作函数的参数。让我们看一个例子来说明:
const lunchObj = {
food: 'tacos',
drink: 'water'
}
function sayLunch(location){
console.log(`I had ${this.food} and ${this.drink} for lunch at ${location}`)
}
sayLunch.call(lunchObj, "Taco Bell") // I had tacos and water for lunch at Taco Bell
嗯,玉米卷听起来不错🤤。如果函数接受多个参数,我们也可以传递它们:
function sayLunch(location, company, time){
console.log(`I had ${this.food} and ${this.drink} for lunch at ${location} with ${company} in the ${time}`)
}
sayLunch.call(lunchObj, "Taco Bell", "Jon and Juan", "afternoon") // I had tacos and water for lunch at Taco Bell with Jon and Juan in the afternoon
使用 apply
apply
工作原理类似call
。唯一的区别是它们接受函数参数的方式。apply
使用数组而不是逗号分隔:myFunction.apply(obj, [arg1, arg2, argn])
使用我们之前的示例,但使用apply
:
const lunchObj = {
food: 'tacos',
drink: 'water'
}
function sayLunch(location, company, time){
console.log(`I had ${this.food} and ${this.drink} for lunch at ${location} with ${company} in the ${time}`)
}
sayLunch.apply(lunchObj, ["Taco Bell", "Jon and Juan", "afternoon"])
我们可以利用apply
ES6 的扩展运算符来利用数组参数
以下是从 mozilla 页面厚颜无耻地复制粘贴的内容:
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
记住,我们可以在内置函数中使用call
and/or ,而不是自定义函数。像这样:apply
const someArr = ["foo", "bar", "baz"];
console.log.apply(null, someArr) // foo bar baz
如果我们想要更进一步,并在其中附加一个新参数someArr
:
console.log.apply(null, ['hello', ...someArr]) // hello foo bar baz
如何记住 call 与 apply 参数
记住哪个是哪个的诀窍是看它们的首字母(来源SO)
- A - >应用->数组
- C ->逗号- >全部
我们只是触及了表面,但希望这足以将您的知识应用到更高级的东西(双关语😎)!
资源/更多阅读材料:
- 使用“apply”模拟 JavaScript 即将推出的扩展运算符
- 理解 JavaScript 中的 This、Bind、Call 和 Apply
Function.prototype.call()
Function.prototype.apply()
- call 和 apply 有什么区别?
- JavaScript 中的 Function.apply 和 Function.call