js方法中嵌套函数的 this 作用域

//不使用箭头函数时  嵌套函数中 内部函数不继承外部函数this
  const o = {
    m:function(){                // 对象的方法m
      let self=this;                // 把this保存在变量中
      console.log(this===o)        // true
      f();//调用嵌套函数
      function f(){//嵌套函数f
        console.log(this === o)    // flase: this 是全局对象 或 underfined(严格模式)
        console.log(self === o)    // true:   self 是外部的 this 值
      }
    }
  }
 o.m() //执行对象o的方法m

//使用箭头函数 继承外部this
const o = {
      m: function () {                // 对象的方法m
        let self = this;                // 把this保存在变量中
        console.log(this === o)    // true
        const f=()=> {//嵌套函数f
          console.log(this === o)     // true:  箭头函数继承外部的this
          console.log(self === o)     // true:   self 是外部的 this 值
        }
        f();//调用嵌套函数 函数表达式创建的方法 需要在方法声明后才能调用
      }
    }
 o.m() //执行对象o的方法m

//使用bind()方法  把函数绑定到了外部的this
const o = {
      m: function () {                // 对象的方法m
        let self = this;                // 把this保存在变量中
        console.log(this === o)       // true
        const f=(function(){//嵌套函数f
          console.log(this === o)     // true:  把函数绑定到了外部的this
          console.log(self === o)     // true:   self 是外部的 this 值
        }).bind(this);
        f();//调用嵌套函数 函数表达式创建的方法 需要在方法声明后才能调用
      }
    }
o.m() //执行对象o的方法m

 

posted @ 2021-09-09 14:28  暴燥的小蓝鲸  阅读(320)  评论(0)    收藏  举报