javascript - Ein Problem mit dem JS-Aufruf, sehr einfacher Code, wie ist das Ausgabeergebnis zu interpretieren?
phpcn_u1582
phpcn_u1582 2017-06-26 10:50:10
0
6
677

foo2() verwendet eine Pfeilfunktion.
Nach dem Verständnis von call sollte foo.call({id:23}) 23 und nicht 0 ausgeben. Kann mir das jemand erklären?
Der Code lautet wie folgt:
<script type="text/javascript">

    function foo() {
        setTimeout(function (){
            console.log('id1:', this.id);
        }, 100);
    }
    
    function foo2() {
        setTimeout(() => {
            console.log('id2:', this.id);
        }, 100);
    }
    
    var id = 0;
    foo.call({id:23});
    foo2.call({id: 2});

</script>

Ausführungsergebnis:
0
2

phpcn_u1582
phpcn_u1582

Antworte allen(6)
迷茫

foo 函数里面的 this 还是 {id:23} 但是到了 setTimeout 接受的回掉里面, this 就变为了 window 所以就输出了全局的 0,第二个因为箭头函数,thisfoo2this 绑定,所以是 2

typecho

foo2的setTimeout的参数是一个箭头函数,里面的this,绑定定义时所在的作用域(foo2执行的时候,this是call中对象),而不是指向运行时所在的作用域。普通的setTimeout中的函数绑定的是运行时作用域(window)。

代言

1、foo函数的this是window,foo2函数的this是{id: 2}这个对象。

巴扎黑

很明显,第一个this指向的是window,而第二个箭头函数this指向当前对象,也就是说谁调用,就指向谁;
第一个可以改下解决下:

    function foo() {
        var _this = this;
        setTimeout(function (){
            console.log('id1:', _this.id);
        }, 100);
    }
    var id = 0;
    foo.call({id:23});
曾经蜡笔没有小新

1、setTimeout中的回调函数在foo执行100ms后执行,运行时的作用域是window。
2、箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。

伊谢尔伦

箭头函数作用域的问题

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!