– call、apply、bind都是改变this指向的方法
方法定义
- apply: 调用一个对象的一个方法,用另一个对象替换当前对象,例如: B.apply(A, arguments),即A对象应用B对象的方法
- call: 调用一个对象的一个方法,用另一个对象替换当前对象。例如:B.call(A, arguments);即A对象调用B对象的方法
上面的定义看一遍是很懵的,不过自己边写例子反复读的时候,会有种拨开云雾的感觉。
call & apply的相同点:
- 方法含义是一样的,即方法功能是一样的;
- 第一个参数的作用是一样的;
call & apply的不同点:两者传入的列表形式不一样
- call 可以传入多个参数;
- apply只能传入两个参数,所以其第二个参数往往是作为数组形式传入
call中的细节
- 非严格模式
如果不传参数,或者第一个参数为null或undefined,this的指向都是window
let fn = function(a,b){
console.log(this,a,b);
}
let obj = {name:"obj"};
fn.call(obj,1,2); // this:obj a:1 b:2
fn.call(1,2); // this:1 a:2 b:undefined
fn.call(); // this:window a:undefined b:undefined
fn.call(null); // this=window a=undefined b=undefined
fn.call(undefined); // this=window a=undefined b=undefined
复制代码
- 严格模式
第一个参数指向谁,this就指向谁,包括null&undefined,如果不传参数this就是undefined
"use strict"
let fn = function(a,b){
console.log(this,a,b);
}
let obj = {name:"obj"};
fn.call(obj,1,2); // this:obj a:1 b:2
fn.call(1,2); // this:1 a:2 b=undefined
fn.call(); // this:undefined a:undefined b:undefined
fn.call(null); // this:null a:undefined b:undefined
fn.call(undefined); // this:undefined a:undefined b:undefined
复制代码
apply
apply : 和call基本一致,唯一的区别在于传参方式
apply把需要传递给fn的参数放到一个数组(或者类数组)中传递进去,虽然写的是一个数组,但是也相当于给fn一个个的传递
fn.call(obj, 1, 2)
fn.apply(obj, [1, 2])
复制代码
bind
bind: 语法和call一模一样,区别在于立即执行还是等待执行,bind不兼容IE6~IE8
fn.call(obj, 1, 2); // 改变fn中的this,并且把fn立即执行
fn.bind(obj, 1, 2); // 改变fn中的this,fn并不执行
复制代码
this改变为obj了,但是绑定的时候立即执行,当触发点击事件的时候执行的是fn的返回值undefined
document.onclick = fn.call(obj);
复制代码
bind会把fn中的this预处理为obj,此时fn没有执行,当点击的时候才会把fn执行
document.onclick = fn.bind(obj);
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END