this调用分类
外部调用
在函数里面使用this,例如
function fun(a){
this.a = a;
}
外部函数里调用this都指向window全局变量,相当于window.a
内部调用obj.func()
就是在一个方法里面调用this,指向的是对象本身。例如array.sort(),array.concat等都是方法调用。
var obj = {
a:'aaaa',
func:function(b){
this.b = b;
return this.b;
}
}
obj.func('bbb'); //this指向obj
console.log(obj.b);//输出bbb
嵌套内部调用
var obj ={
a:'aaa',
func:function(b){
this.b = b;
function interal(c){
this.c = c;
console.log(this === obj);//false
return this.c;
}
return interal;
}
};
var fun1 = obj.func();//返回interal函数
fun1('cccc'); //false
因为内部interal函数已经脱离了对象,相当于外部调用,因此其this指向window
解决办法
使用func1.call(obj,’ccc’),将函数与obj对象进行绑定
陷阱
看下面的代码
var obj = {
a:'aaa',
func:function(){
console.log(this === obj);//false
}
}
setTimeout(obj.func,1000);
因为obj.func经历了一次参数传值的过程,func已经从obj分离了,相当于var func1 = obj.func;func1();
隐式调用
函数都有call()和apply()方法,两者区别是,apply(obj,[arg1,arg2,…]),call(obj,arg1,arg2,…);call后接的是一个数组。
绑定函数
绑定函数是与对象绑定的函数,绑定函数与原函数共享作用域,但在执行时有不同的上下文。
方法.bind(thisArgs,[arg1,arg2,…]),接收第一个参数作为上下文,并且有一组可选的参数。看个例子
function multiply(number){
'use strict'
return this * number;
}
var double = multiply.bind(2);//将2绑定给函数
double(3);//6
double(5);//10
与call()和apply()不同,bind()不是立即执行,而是先绑定参数,返回一个新的函数。
在调用绑定函数时,this是bind的第一个参数
bind绑定后,会永久保持绑定,通过apply()或call()不能改变其绑定关系,甚至是再次绑定也不起作用
function func(){
return this;
}
var a = func.bind(1);
a();//1
a.call(2);//1
a.apply(2);//1
var b = func.bind(2);
b();//1
箭头函数中的this
箭头函数中的this跟定义时上下文有关。例如
class point{
constructor(x,y){
this.x = x;
this.y = y;
}
log(){
console.log(this === myPoint);//true
setTimeout(()=>{
console.log(this === myPoint);//true
console.log(this.x+":"+this.y);
},1000);
}
}
var myPoint = new point(95,166);
myPoint.log();