1.this定义
函数的this关键字在javaScript中的表现略有不同,在严格模式和非严格模式之间也不相同
大多数情况下,函数的调用方式决定了this的值(运行时绑定,但箭头函数是在定义时就确定,并且后续无法改变)
this关键字是函数运行时自动生成的一个对象,只能在函数内部使用,总指向调用它的对象
2.绑定规则
1.显示绑定
2.默认绑定
3.隐式绑定
4.new绑定
默认绑定
let name = 'aDong'
function person(){
return this.name
}
console.log(person());//aDong
此时函数中的this指向window,但在严格模式下,不能将全局对象用于默认绑定,this会绑定undefined,只有函数在非严格模式下才能绑定到全局对象
隐式绑定
function test(){
console.log(this.x);
}
var obj = {}
obj.x = 1
obj.f = test
obj.f()//1
var o = {
a:10,
b:{
fn:function(){
console.log(this.a);//undefined
}
}
}
o.b.fn()
尽管fn是被最外层对象调用,但是此时this指向的是b对象,b对象中无a属性
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this);//window
console.log(this.a);//undefined
}
}
}
let m = o.b.fn
m()
this永远指向的是最后调用它的对象,赋值时并没有执行函数,没有绑定this
new绑定
function test(){
this.x = 1
}
var obj = new test()
console.log(obj.x);//1
如果函数返回一个对象,则this指向返回对象,若返回一个数值或null,那么this还是指向test
function test(){
this.x = 1
return {}
}
var obj = new test()
console.log(obj.x);//undefined
显示修改
call(),bind(),apply()但是不能用于箭头函数
优先级
new绑定 > 显示绑定 > 隐式绑定 > 默认绑定