call,apply,bind用法和区别
call、apply
调用时直接执行函数
function fn(){
console.log('aa')
}
fn.call()//执行函数
fn.apply()//执行函数
当写入参数时,第一个参数为当前执行函数时this指向,也就是说它可以改变当前的this 指向,如果第一个参数带入的不是对象,会自动转换为对象,想数字类型会转换成Number,字符类型会转换为String等。
function fn(a,b,c){
console.log('this,a+b+c')
}
var obj = {a:1}
fn.call(obj)//改变当前this指向,当前this指向obj,并执行函数
fn.apply(obj)//改变当前this指向,当前this指向obj,并执行函数
call和apply的区别在于他们后续的参数
function fn(a,b,c){
console.log('this,a+b+c')
}
var obj = {a:1}
fn.call(obj,1,2,3)//第一个参数是函数中this指向的对象,后面会按顺序带入参数
fn.apply(obj,[1,2,3])//apply只有两个参数,第一个参数是this指向的对象,第二个参数是函数所需的所有参数的数组,列表
bind
当我们在使用回调函数时,使用call和apply会出现一些问题,因为call和apply会直接执行我们的回调函数,我们需要的时候在我们需要的时候执行,这个时候就不能使用call和apply,如果我们需要在回调函数中改变当前this指向时,这个时候就需要用bind
bind一般用于回调函数的传参,它可以绑定当前函数中this的指向。
var obj={a:1};
setTimeout((function(){
console.log(this);
}).bind(obj),1000);
this指向问题
1、全局中this代表window
console.log(this)
2、函数中的this指向
function fn(){
console.log(this)
}
在ES5非严格模式下,全局中this和函数中this都指向window
ES5严格模式,ES6,全局中this仍然指向window,函数中this指向undefined。
3、对象中的this
var obj = {
a:1,
b:funciton(){
console.log(this)//当前this指向当前对象obj,不会因为变量的引用而改变。
},
c:this.a//this指向对象外this的指向,因为此时对象还没有创建完成,this还没有生成。
}
4、回调函数中的this
var obj = {
a:function(){
function fn1 (fn){
fn()//如果直接执行回调函数时,this指向最外层window。
arguments[0]()//如果通过arguments直接使用参数指向函数,this则指向当前函数的arguments。
}
function fn2 (){
console.log(this)//如果回调函数通过call,apply,bind重新指向了新的对象时,this就是指向新对象。
}
fn1(fn2)
}
}
5、事件中的this
var obj = {
a:1,
b:function(){
document.addEventListener('click',this.clickHandler)//特殊的回调函数
document.attachEvent('onlick',this.clickHandler)//ie中的事件侦听
},
clickHandler:function(e){
console.log(this)//事件侦听的对象 e.currentTatget.
console.log(this)//在ie中attachEvent侦听时,this指向window
}
}
6、ES6类中的this
class Box{
constructor(){
console.log(this)//指向被实例化的对象
}
play(){
console.log(this,"|");//指向被实例化的对象
}
static run(){
console.log(this);
// this就是当前类名也是构造函数
// 任何的静态方法中this都是当前类
// 静态方法中无法获取到实例化对象的this的
}
}
7、ES5面向对象中的this
funcntion Box(){
console.log(this)
}
Box.prototype.play=function(){
console.log(this);//this是指向执行该方法的实例化对象
}
Box.run=function(){
console.log(this);//Box
}
// Box();//this是window或者undefined
var b=new Box();// this是实例化后b对象
8、箭头函数中的this
var obj = {
a: function () {
setTimeout(() => {
console.log(this);//this是箭头函数外this的指向
// 上下文环境中this的指向 就是obj
}, 2000);
},
}
var obj={
a:function(){
console.log(this);//obj
},
b:()=>{
console.log(this);//window
}
}
9、call,apply,bing
function fn(){
console.log(this);
}
var obj={a:1}
fn.call(obj);//fn中this指向obj
fn.apply(obj);//fn中this 指向obj
fn.bind(obj)();//fn中this指向obj
//如果是call apply bind 带入的是null,将会把这里的this重新指向window