apply和call两种调用方式中的this指向,表现出来的特征就是:对象可以‘借用’其他对象的方法
obj对象有一个方法fn,obj1想借用obj的方法fn,可以用obj.fn.apply(obj1)
1、apply
在使用apply方式使用一个函数时
- 第1个参数为thisObject,调用时采用传入的thisObject代替函数体中this的指向
- 第2个参数传入一个数组,函数会用数组的值取代"参数列表"
如果第一个传入的参数是null,那么,在函数体内的this会指向全局对象,在浏览器中就是window
2、call
call方式和apply方式的差别主要体现在传入的形式参数的不一样
当采用call调用的时候
- 第1个参数传入thisObject
- 第2个参数以及后面的参数组成'实参列表'传递给函数。
3、bind
和call很相似
- 第一个参数是this的指向
- 从第二个参数开始是接收的参数列表
区别在于bind方法返回值是函数以及bind接收的参数列表的使用。call 是把第二个及以后的参数作为 fn 方法的实参传进去,而 fn1 方法的实参实则是在 bind 中参数的基础上再往后排。
bind 方法不会立即执行,而是返回一个改变了上下文 this 后的函数。
根据代码理解
function fn(name) {
this.name = name
}
var obj = {}
fn.call(obj) //fn函数中的this指向obj
console.log(fn.call(obj)) //undefined
console.log(obj) // {name: undefined}
console.log(fn.call(obj, 'name')) //undefined
console.log(obj) // {name: name}
console.log(fn.apply(obj, ['name'])) //undefined 注意:apply第二个参数是数组
console.log(obj) // {name: name}
console.log(fn.bind(obj, 'name')) // fn(name){this.name =name} 返回值是一个函数
console.log(obj) // {} 注意bind不会立即执行
console.log(fn.bind(obj, 'name')()) // fn(name){this.name =name} 返回值是一个函数
console.log(obj) // {name: name}