【面试题】 JavaScript 中 call()、apply()、bind() 的用法

在JavaScript学习过程中,经常会看到这三个函数的使用,但是却并不是了解他们的具体使用和区别。这次做笔记分享一下,同时也让自己加深一下记忆。

call

call()  方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

语法:

// thisArg: 可选,在 function 函数运行时使用的 this 值
// arg1, arg2, ... :可选: 指定的参数列表
function.call(thisArg, arg1, arg2, ...)

示例:

let person1 = { 
  firstName: "John", 
  lastName : "Doe", 
  fullName: function (args1, args2) {
    // 在方法中,不改变this指向的情况下,this 表示该方法所属的对象,也就是person1
    return this.firstName + " " + this.lastName 
    + " " + args1 + " " + args2;
  } 
}
var person2 = { 
  firstName:"Tom", 
  lastName: "Liming", 
} 
let result = person1.fullName.call(person2, 'a', 'b')
console.log(result) // Tom Liming a b

apply

apply() 方法调用一个具有给定 this 值的函数,以及以一个数组的形式提供的参数。 虽然这个函数的语法与 call() 几乎相同,但根本区别在于,call()接受一个参数列表,而 apply() 接受一个参数的单数组。

语法:

// thisArg: 在 func 函数运行时使用的 this 值。
// argsArray: 可选,一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 func 函数。
apply(thisArg, argsArray)

示例:

let person1 = { 
  firstName: "John", 
  lastName : "Doe", 
  fullName: function (args) {
    return this.firstName + " " + this.lastName 
    + " " + args[0] + " " + args[1];
  } 
}
var person2 = { 
  firstName:"Tom", 
  lastName: "Liming", 
}
let result = person1.fullName.call(person2, ['a','b'])
console.log(result) // Tom Liming a b

bind

bind()  方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用

语法:

bind(thisArg, arg1, arg2, /* …, */ argN)

示例:

let person1 = { 
  firstName: "John", 
  lastName : "Doe", 
  fullName: function (args1, args2) {
    return this.firstName + " " + this.lastName 
    + " " + args1 + " " + args2;
  },
  getfullName: function (args) {
    return this.firstName + " " + this.lastName 
    + " " + args[0] + " " + args[1];
  } 
}
var person2 = { 
  firstName:"Tom", 
  lastName: "Liming", 
} 
let result1 = person1.fullName.bind(person2, 'a', 'b')()
let result2 = person1.getfullName.bind(person2, ['a','b'])()
console.log(result1) // Tom Liming a b
console.log(result2) // Tom Liming a b

总结

  1. 三者均可以改变函数体内部this的指向。
  2. 第一个参数都是 this 的指向对象,如果没有这个参数或参数为undefined或null,则this指向全局的window。
  3. 传参的形式不同,apply的参数要放在数组中传入,call的参数是列表形式(以逗号分割),bind的参数可以是列表形式也可以是数组形式,apply和call是一次性传入,而bind可以分多次传入
  4. bind返回的是有指定的 this值和初始参数的原函数拷贝,便于稍后调用,apply、call则是立即调用。

 给大家推荐一个实用面试题库

1、前端面试题库 (面试必备)            推荐:★★★★★

地址:前端面试题库

猜你喜欢

转载自blog.csdn.net/weixin_42981560/article/details/127085345
今日推荐