Heim  >  Fragen und Antworten  >  Hauptteil

javascript - Ein Problem mit dem JS-Aufruf, sehr einfacher Code, wie ist das Ausgabeergebnis zu interpretieren?

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_u1582phpcn_u15822648 Tage vor686

Antworte allen(6)Ich werde antworten

  • 迷茫

    迷茫2017-06-26 10:52:10

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

    Antwort
    0
  • typecho

    typecho2017-06-26 10:52:10

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

    Antwort
    0
  • 代言

    代言2017-06-26 10:52:10

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

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-06-26 10:52:10

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

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

    Antwort
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-26 10:52:10

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

    Antwort
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-26 10:52:10

    箭头函数作用域的问题

    Antwort
    0
  • StornierenAntwort