call,apply,bind再一次整理

call,apply,bind 到底是用来干嘛的?

每次看到这几个方法,都不能很快的跳出他们的作用及区别。因为实战中用的太少,不过还是要再次整理一下,以备后用。
1.借用别人的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var Fruits = {
name: 'Fruits',
say: function(){
console.log('im ' + this.name);
}
}

var Apple = {
name: 'apple'
}

Fruits.say();
Fruits.say.call(Apple);
Fruits.say.apply(Apple);

2.数组之间追加

1
2
3
4
var array1 = [12 , "foo" , {name: "Joe"} , -2458]; 
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
console.log(array1);

3.代理方法
比如写一个 log 函数,用于实现 console.log

1
2
3
4
5
6
function log(){
//注意 arguments 不是数组!直接 console.log(arguments) 无效
console.log.apply(console, arguments);
}

log(1);

如果想在每个 console.log 前加个前缀

1
2
3
4
5
6
7
8
function log(){
var args = Array.prototype.slice.call(arguments); //转为标准数组
args.unshift('(app)');

console.log.apply(console, args);
}

log(1);

call 和 apply 有什么区别?

其实功能一样,只是 apply 的第二个参数接受数组,不需要知道传入的个数,包装成数组即可

1
2
3
4
5
6
var func = function(arg1, arg2) {

};

func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2]);

bind 有什么用?

首先 bind 是什么?MDN的解释是:bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

挖槽这怎么看的懂???上代码

1
2
3
4
5
6
7
8
9
var foo = {
bar : 1,
eventBind: function(){
var _this = this;
$('.someClass').on('click',function(event) {
console.log(_this.bar);
});
}
}

以上代码很容易理解,this 发生了变化,所以必须将 this 赋予 _this

使用 bind 改造这段代码

1
2
3
4
5
6
7
8
var foo = {
bar : 1,
eventBind: function(){
$('.someClass').on('click',function(event) {
console.log(this.bar);
}, bind(this));
}
}

在上述代码里,bind() 创建了一个函数,当这个click事件绑定在被调用的时候,它的 this 关键词会被设置成被传入的值(这里指调用bind()时传入的参数)。因此,这里我们传入想要的上下文 this(其实就是 foo ),到 bind() 函数中。然后,当回调函数被执行的时候, this 便指向 foo 对象。

bind call apply 区别

1
2
3
4
5
6
7
8
9
10
11
12
13
var bar = function(){
console.log(this.x);
}

var foo = {
x: 5
}

bar.bind(foo)();

bar.apply(foo);

bar.call(foo);

其实 call,apply,bind 的作用都是改变 this 的指向,只是 bind 需要调用执行,apply 和 call 会立即执行。