【面试题】JavaScript 中 call()、apply()、bind() 的用法 您所在的位置:网站首页 javaweb题库 【面试题】JavaScript 中 call()、apply()、bind() 的用法

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

2023-05-01 12:41| 来源: 网络整理| 查看: 265

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

大厂面试题分享 面试题库 前后端面试题库 (面试必备) 推荐:★★★★★

地址:前端面试题库  web前端面试题库 VS java后端面试题库大全

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'])() // 参数分两次传入例子 let func = person1.fullName.bind(person2, 'hello') // 执行返回函数 let result3 = func(['world']) console.log(result1) // Tom Liming a b console.log(result2) // Tom Liming a b console.log(result3) // Tom Liming hello world 复制代码 总结 三者均可以改变函数体内部this的指向。第一个参数都是 this 的指向对象,如果没有这个参数或参数为undefined或null,则this指向全局的window。传参的形式不同,apply的参数要放在数组中传入,call的参数是列表形式(以逗号分割),bind的参数可以是列表形式也可以是数组形式,apply和call是一次性传入,而bind可以分两次传入bind返回的是有指定的 this值和初始参数的原函数拷贝,便于稍后调用,apply、call则是立即调用。 大厂面试题分享 面试题库 前后端面试题库 (面试必备) 推荐:★★★★★

地址:前端面试题库  web前端面试题库 VS java后端面试题库大全



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有