首页 > 要输出正确的myName的值要如何修改程序?为什么呢?

要输出正确的myName的值要如何修改程序?为什么呢?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
        foo = function(){

            this.myName = "Foo function.";

        }

        foo.prototype.sayHello = function(){

            alert(this.myName);

        }

        foo.prototype.bar = function(){

            setTimeout(this.sayHello, 300);

        }

        var f = new foo;

        f.bar();
    </script>
</body>
</html>

这么改:

<script>
    var foo = function(){

        this.myName = "Foo function.";

    };

    foo.prototype.sayHello = function(){

        alert(this.myName);

    }

    foo.prototype.bar = function(){

        setTimeout(this.sayHello.bind(this), 300);

    }

    var f = new foo;

    f.bar();
</script>

因为当你把this.sayHello传给setTimeout后,this指针变了,所以需要用bind强制绑定到当前的this


foo.prototype.bar = function(){
    
    setTimeout(function(){this.sayHello.bind(this)}, 300);

}

foo.prototype.bar = function(){
    var _this = this;
    setTimeout(function(){
        _this.sayHello();
    }, 300);
}

ES6写法

foo.prototype.bar = function(){
    setTimeout(() => this.sayHello(), 300);
  };
【热门文章】
【热门文章】