区别bind()与call()和apply()?
相同点: * 都是用来改变函数的this对象的指向的
* 第一个参数都是this要指向的对象
* 都可以利用后续参数传参
不同点:
* call()/apply()是立即调用函数,而bind()返回函数,所以后面还需加括号来调用
* 参数区别
call 方法第一个参数是要绑定给this的值,后面传入的是一个参数列表。当第一个参数为null、undefined的时候,默认指向window。
apply接受两个参数,第一个参数是要绑定给this的值,第二个参数是一个参数数组。当第一个参数为null、undefined的时候,默认指向window。
和call很相似,第一个参数是this的指向,从第二个参数开始是接收的参数列表。区别在于bind方法返回值是函数以及bind接收的参数列表的使用。
var obj = {}
function foo(num1, num2) {
console.log(num1, num2)
console.log(this)
}
// foo(1, 2) //this指window
// foo.call(obj, 3, 4) 或Person.call(this,name,age) //让任意函数成为任意对象的方法
// foo.apply(obj, [5 ,6])
// foo.bind(obj, 7, 8)()
setTimeout(function () {
console.log(this)
}.bind(obj), 1000)
var Person1 = function () {
this.name = 'Dot';
}
var Person2 = function () {
this.getname = function () {
console.log(this.name);
}
Person1.call(this);
}
var person = new Person2();
person.getname(); // Dot
因为在 Person2 中,Person1.call(this) 的作用就是使用 Person1 对象代替 this 对象,那么 Person2 就有了 Person1 中的所有属性和方法了,相当于 Person2 继承了 Person1 的属性和方法。
var obj = {
name: 'Dot'
}
function printName() {
console.log(this.name)
}
var dot = printName.bind(obj)
console.log(dot) // function () { … }
dot() // Dot
bind 方法不会立即执行,而是返回一个改变了上下文 this 后的函数。
而原函数 printName 中的 this 并没有被改变,依旧指向全局对象 window。
参数的使用
function fn(a, b, c) {
console.log(a, b, c);
}
var fn1 = fn.bind(null, 'Dot');
fn('A', 'B', 'C'); // A B C
fn1('A', 'B', 'C'); // Dot A B
fn1('B', 'C'); // Dot B C
fn.call(null, 'Dot'); // Dot undefined undefine