zoukankan      html  css  js  c++  java
  • 一个有意思的this指向问题

    首先来看一段代码:

    function LateBloomer() {
      this.petalCount = Math.ceil(Math.random() * 12) + 1;
    }
    
    // Declare bloom after a delay of 1 second
    LateBloomer.prototype.bloom = function() {
      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'方法
    

    在bloom中,为什么要这样写呢?

    this.declare.bind(this)
    首先,这里的this指的是LateBloomer构造函数所要实例化的对象,即:

    this.declare = function() {
      console.log('I am a beautiful flower with ' +
        this.petalCount + ' petals!');
    };
    

    若这么写:

    setTimeout( function() {
      console.log('I am a beautiful flower with ' +
        this.petalCount + ' petals!');
    }, 1000);
    

    setTimeout的回调函数内部的this指向的是window,但petalCount属性是属于LateBloomer的instance,所以要用bind把this的指向变回来。

  • 相关阅读:
    c++第十八章-(容器和算法)
    07表与表之间的关系
    06约束
    01 Hello World!
    05文件合并脚本--By Mark Lutz
    04文件分割器脚本
    05数据库用户操作
    03扫描模块搜索路径
    02扫描目录树
    01扫描单个目录
  • 原文地址:https://www.cnblogs.com/arduka/p/12823035.html
Copyright © 2011-2022 走看看