0%

console的apply,call,bind

console的apply,call,bind

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// apply call bind 是用来给函数指定 this 用的
// 但是用法稍有区别, 以我们长久以来使用的 log 为例
var log = function() {
// log 是一个函数
// js 中的函数是一个对象
// 所以函数可以有方法
// apply, call, bind 都是函数的方法, 用来指定 this
//
// apply 接受两个参数
// 第一个参数是函数里面的 this, 这里指定了是 console, 这样就相当于 console.log
// 第二个参数是要传给函数的参数列表, 类型是 数组
// apply 会把数组拆成一个个的参数传给函数
// 假设你调用 log(1, 2, 3, 4)
// 那么 arguments 是 [1, 2, 3, 4] 这样的一个数组
// (实际上 arguments 不是数组, 但是表现和数组一模一样, 你就暂时当它是一个数组)
// 下面这句就相当于调用 console.log(1, 2, 3, 4)
// console.log.apply(console, [1, 2, 3, 4])
console.log.apply(console, arguments)

// call 和 apply 类似, 但是小有区别, 如下
// 第一个参数和 apply 一样
// 第 2, 3, 4, 5, ... 个参数会依次作为参数传给函数
console.log.call(console, 1, 2, 3, 4)
// 相当于调用下面的函数, 区别在于参数的类型
// console.log.apply(console, [1, 2, 3, 4])
// 相当于调用 console.log(1, 2, 3, 4)
// var print = console.log
// print.call(console, 1, 2, 3)
}

// bind 函数不直接调用, 而是返回一个函数让你来调用
// 第一个参数是用来指定函数里面的 this, 和 apply call 一样
// 用法就是这样, 返回一个指定了 this 的函数
// 下面的例子中, bind 函数把 console 参数指定为 log 函数的 this
var log = console.log.bind(console)
log('hello', 1, 2, 3)
// hello 1 2 3


// bind 还可以有额外的参数, 效果如下
// 给返回的函数加上部分参数
var error = console.log.bind(console, '*** ERROR')
// 下面的调用相当于 console.log('*** ERROR', '错误')
error('错误')
// *** ERROR 错误