> 文章列表 > javaSccript---call()、 bind()、 apply()的区别

javaSccript---call()、 bind()、 apply()的区别

javaSccript---call()、 bind()、 apply()的区别

call()、apply()、bind() 都是用来重定义 this 这个对象的

语法:

function.apply(thisArg, [argsArray])//argsArray 是一个可选的数组

function.call(thisArg, arg1, arg2, ...)//arg1、arg2、... 是将传递给函数参数列表

function.bind(thisArg, arg1, arg2, ...)//arg1、arg2、... 是一些可选的参数,这些参数将在调用新函数时作为参数列表传递给原函数

function test(a, b) {console.log(a + b);
}
test.call({ name: "call" }, 1, 2); //3
test.apply({ name: "apply" }, [2, 3]); ///5
const test1 = test.bind({ name: "bind" }, 4);
console.log(test1); //[Function: bound test]
test1(2); //6

相同点:第一个参数thisArg 表示函数要绑定的上下文,是用来改变函数this指向的,第二个参数是是用于传参

不同点:

call 和apply可以直接调用,bind不会立即调用函数,而是会返回一个新的函数

call和bind可以传递多个参数,apply只能传递一个参数 (数组或者伪数组)

JavaScript 中 call()、apply()、bind() 的用法 | 菜鸟教程其实是一个很简单的东西,认真看十分钟就从一脸懵B 到完全 理解! 先看明白下面: 例 1 obj.objAge; // 17 obj.myFun() // 小张年龄 undefined 例 2 shows() // 盲僧 比较一下这两者 this 的差别,第一个打印里面的 this 指向 obj,第二个全局声明的 shows() 函数 this 是 window ; 1,call()、appl..https://www.runoob.com/w3cnote/js-call-apply-bind.html