js的this指向问题探究

172 阅读2分钟

定义

this关键字是函数运行时自动生成的一个内部对象。根据this运行环境的不同,this指向也不同。谁调用,this指向谁。 据此,我们可以把this指向分为以下四种情况:

  1. 默认绑定
  2. 隐式绑定
  3. 显式绑定
  4. new绑定

那么首先我们来看:

默认绑定

var  a = 2
function getNumber(){
    console.log(this.a)
}
getNumber()
// 2
window.getNumber()
//2

解析:因为getNumber在全局中调用,this指向的是window。

隐式绑定

函数作为某个对象的方法调用,这时this指向这个对象

var obj = {
    j: 10,
    b:{
      fn:function(){
       console.log(this.j)
     }
    }
}
obj.b.fn()
//打印b,因为this指向的是其上下文对象b。

//注意:存在特殊情况
var  mm = obj.b.fn
mm()
//打印的则是window,this指向最后调用它的对象,mm()在全局中调用了this。

显示绑定

通过apply()、call()、bind()方法改变函数的调用对象,它的第一个参数作为调用函数的对象。

var y = 10;
function test(){
    console.log(this.y)
    return this.y
}
var obj  ={}
obj.y = 1;
obj.m = test;
obj.m()  //1
obj.m.apply(this)  == window.y  //turn
//test里面this指向被修改为全局对象

new绑定

new关键字调用函数时,执行如下步骤:

  1. 创建(或者说构造)一个全新的对象。
  2. 这个新对象会被执行 [[Prototype]] 连接。
  3. 这个新对象会绑定到函数调用的 this。
  4. 如果函数没有返回其他对象,那么 new 表达式中的函数调用会自动返回这个新对象。(即后面的特殊情况例子)

构造函数的this指向实例化对象

function test(){
 this.x = 1
}
var obj = new test()
obj.x
//1

特殊情况:当new过程遇到返回一个对象,这时候this指向的是返回对象

function fn(){
    this.user = 'xxx';;
    return {}
}
var a = new fn;
console.log(a.user) //undefined

最后,绑定规则优先级:new>>>显式>>隐式>>默认。