s

this指向问题

  • 定时器  settimeout 中this 指向  非严格模式指向 window对象  严格模式指向 undefined
    其实也是因为 定时器回调是在window  全局被执行的  this 指向函数 运行的环境  

    但不绝对:

    (1)hello直接调用者是obj,第一个this指向obj,setTimeout里匿名函数没有直接调用者,this指向window

    const obj = {
        num: 10,
       hello: function () {
        console.log(this);    // obj
        setTimeout(function () {
          console.log(this);    // window
        });
       }    
    }
    obj.hello();

    (2)hello直接调用者是obj,第一个this指向obj,setTimeout箭头函数,this指向最近的函数的this指向,即也是obj

    const obj = {
        num: 10,
       hello: function () {
        console.log(this);    // obj
        setTimeout(() => {
          console.log(this);    // obj
        });
       }    
    }
    obj.hello();

     

  • 普通函数中 this 指向函数  this 指向  非严格模式指向 window对象  严格模式指向 undefined
    function test(){}
    test() // 这里同样指向window 严格模式 undefined

     

  • 对象中的方法,直接调用 对象中的方法, 方法中的this 指向 调用该方法的对象!!!
    const obj = {
    func: function(){
    }  
    }
    obj.func() => this 指向 obj

     

  • 箭头函数中 this 的指向
    箭头函数中 this 指向 函数被创建时(被定义出来的)的那个环境
    ES6箭头函数里this的指向就是上下文里对象this指向,偶尔没有上下文对象,this就指向window

    (2)hello直接调用者是obj,第一个this指向obj,setTimeout箭头函数,this指向最近的函数的this指向,即也是obj

    const obj = {
        num: 10,
       hello: function () {
        console.log(this);    // obj
        setTimeout(() => {
          console.log(this);    // obj
        });
       }    
    }
    obj.hello();

    (3)diameter是普通函数,里面的this指向直接调用它的对象obj。perimeter是箭头函数,this应该指向上下文函数this的指向,这里上下文没有函数对象,就默认为window,而window里面没有radius这个属性,就返回为NaN。

    const obj = {
      radius: 10,  
      diameter() {    
          return this.radius * 2
      },  
      perimeter: () => 2 * Math.PI * this.radius  =》 this => window
    }
    console.log(obj.diameter())    // 20
    console.log(obj.perimeter())    // NaN
    注意点:call,apply,bind等方法也不能改变箭头函数this的指向

     

  • 事件 ex: click  等 事件函数中的 this 指向触发事件的那个DOM元素!! 

example:【例子来源于 阮一峰老师写的博客】

   

 var name = 'the window';
  var object = {
    name:'the object',
    getNameFunc: function(){
      console.log(this)
      return function(){
        console.log(this)
        return this.name
      }
    }
  }
  alert(object.getNameFunc()()) // =>  the window
/*
  
  object.getNameFunc()  返回的是一个 匿名函数     object.getNameFunc()()  这里其实等同于 普通函数的调用   所以 this 指向window  

*/
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
example2

 var name = "The Window";


  var object = {
    name : "My Object",


    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };


    }


  };


  alert(object.getNameFunc()());  // my object

//object.getNameFunc()  是调用对象中的 方法  this 指向对象  赋值给that  也就是 that == 对象 object 由于闭包  that.name 可以访问到  对象的name   

 


 

posted @ 2021-06-03 15:13  努力不搬砖的iori  阅读(56)  评论(0编辑  收藏  举报