zoukankan      html  css  js  c++  java
  • setTimeout的this问题

    MDN这样描述:

    在默认情况下,使用 window.setTimeout() 时,this 关键字会指向 window (或全局)对象。当使用类的方法时,需要 this 引用类的实例,你可能需要显式地把 this 绑定到回调函数以便继续使用实例。

    function LateBloomer() {
      this.petalCount = Math.ceil(Math.random() * 12) + 1;
    }
    
    // Declare bloom after a delay of 1 second
    LateBloomer.prototype.bloom = function() {
      window.setTimeout(this.declare.bind(this), 1000);
    };
    
    LateBloomer.prototype.declare = function() {
      console.log('I am a beautiful flower with ' +
        this.petalCount + ' petals!');
    };
    
    var flower = new LateBloomer();
    flower.bloom();  // 一秒钟后, 调用'declare'方法


    我之前一直不太明白setTimeout的this既然指向window,为什么bind一下就指向obj对象了
    后来忽然感觉想明白了,收到箭头函数的一点启发,好像是因为在定义的时候,this的确是指向obj对象的,这个时候可以使用this.xxx.bind(this)将xxx函数绑定到只指向obj对象,但是如果不绑定,等到
    setTimeout函数执行的时候,this指向的就是window全局对象了。不知道自己这样理解对不对
  • 相关阅读:
    hibernate
    杨辉三角
    查看端口号
    一个线程同步问题的例子
    SQL关系数据库设计三大范式
    C#OpenFileDialog的使用
    莫队算法
    蒟蒻已知的高能数学公式
    C++ 产生随机数
    C++ 输出小数点后 n 位
  • 原文地址:https://www.cnblogs.com/walei/p/7132928.html
Copyright © 2011-2022 走看看