深度理解几种this调用的指向问题

169 阅读1分钟
  • 作为对象的方法调用。
  • 作为普通函数调用。
  • 构造器调用。
  • Function.prototype.call 或 Function.prototype.apply 调用

以下分别是这几种的调用方式

1

// 作为对象属性
let objThis = {
    name: "ming",
    getName: function() {
      return this.name;
    }
  };

  console.log(objThis.getName()); // ming

2

// 作为普通函数
let obj = objThis.getName
console.log(obj())

3

 // 作为构造函数调用
  function G(){
      this.name = 'mig'
  }
  let oo = new G()
  console.log(oo.name) // mig

  显式返回对象
  function G(){
      this.name = 'mig'
      return {
          name : 'bin'
      }
  }
  let oo = new G()
  console.log(oo.name) // bin

  不返回对象
  function G(){
      this.name = 'mig'
      return 'bin'

  }
  let oo = new G()
  console.log(oo.name) // mig
  

4

  // call apply 改变this指向
let objThis = {
  name: "ming",
  getName: function() {
    return this.name;
  }
};
let obj111 = {
  name: "niuniu"
};
console.log(objThis.getName.call(obj111)); // niuniu

后面的文章更新会慢点啦, 先种草, 后续再补...