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的指向变回来。

  • 相关阅读:
    iOS input disabled显示不清楚
    钉钉小程序——JSAPI
    留言板
    友链
    mysql---存储引擎
    union与limit
    spring--setter注入
    spring---生命周期
    sql03-连接查询
    sql01--认识表
  • 原文地址:https://www.cnblogs.com/arduka/p/12823035.html
Copyright © 2011-2022 走看看