this指向问题对于初学者是一个比较头疼的事,今天我总结了几点关于this指向的问题,也就是我们所说的执行期上下文
1.默认绑定,没人调用指向window
var name = 'window'
function test() {
console.log(this.name)
}
test() //window
2.隐式绑定,谁调用this指向谁
var name = 'window'
var obj = {
name:'obj',
sayName(){
console.log(this.name)
}
}
obj.sayName(); //obj
3.显示绑定,bind,call,apply
在这里我也说一下他们之间的区别,bind返回带有明确this指向的函数,call和apply会立即执行函数并且改变this指向,而call和apply的区别在于传参列表不一样
var name = 'window'
var obj = {
name:'obj',
sayName(){
console.log(this.name)
}
}
obj.sayName() //obj
var sayName = obj.sayName.bind(window)
sayName() //window
sayName.call(obj) //window
4.通过new绑定
function Person(){
this.name = name
console.log(this.name)
}
var person = new Person() //obj
5.优先级比较
显示绑定和隐式绑定
var name = 'window'
var obj = {
name:'obj',
sayName(){
console.log(this.name)
}
}
obj.sayName() //obj
obj.sayName.call(window) //window
可以看出显示绑定>隐式绑定
显示绑定和new绑定
function Person(name){
this.name= name
console.log(this)
}
var p = Person.bind(window)
var newP1 = new p('newP1') //Person{name:'newP1'}
将this硬绑定到window上,可通过new绑定还是改变了this指向,所以new绑定>显示绑定
即new绑定>显示绑定>隐式绑定