0%

js中call()、apply()、bind()的区别及用法

用法

函数 用法
call() call(对象, arg1, arg2, …)
apply() apply(对象,[arg1,arg2, …])
bind() 函数.bind(对象, arg1, arg2, …)
  • 相同点:都是用来改变this的指向
  • 不同点:参数书写方式不同

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
<head></head>
<body></body>
<script type="text/javascript">

let obj = {
name: 'name',
age: 18
};
function fn(x, y) {
console.log(x, y, this);
}

fn.call(obj, 'call-xiao', 'call-ming');
// call-xiao call-ming {name: "name", age: 18}

fn.apply(obj, ['apply-xiao', 'apply-ming']);
// apply-xiao apply-ming {name: "name", age: 18}

let newFn = fn.bind(obj, 'bind-xiao', 'bind-ming');
newFn();
// bind-xiao bind-ming {name: "name", age: 18}

</script>
</html>

call()的应用

  • 利用call()判断数据类型

    1
    2
    let type = Object.prototype.toString.call(12);
    console.log(type);
  • 利用call()翻转字符串

    1
    2
    3
    4
    5
    6
    7
    8
    let str = 'hello';
    // 方式一,方法内有使用call()
    let arr01 = Array.from(str).reverse().join('');
    console.log(arr01); // olleh

    // 方式二
    let arr02 = Array.prototype.reverse.call(str.split('')).join('');
    console.log(arr02); // olleh

apply()的应用

利用apply()求最大值

1
2
3
4
let arr = [1, 4, 2, 3, 9, 7];
let max = Math.max.apply(arr, arr);
// 第一个arr表示让arr借用max这个方法,第二个arr表示传给max的数据
console.log(max); // 9

bind()的应用

对一个函数预设初始参数

1
2
3
4
5
function fn() {
return Array.from(arguments);
}
let newFn = fn.bind(this, 1, 2);
console.log(newFn()); // [1, 2]