Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Arrow函数将更改此函数的上下文_Javascript_Jquery_Ecmascript 6 - Fatal编程技术网

Javascript Arrow函数将更改此函数的上下文

Javascript Arrow函数将更改此函数的上下文,javascript,jquery,ecmascript-6,Javascript,Jquery,Ecmascript 6,箭头函数是否可以重新定义现有函数的行为?使用jQuery的get(是的,我知道)-我得到了两个不同的内部成功值,这取决于是否使用了arrow函数。有人能解释为什么会这样吗 var get = (e) => { return new window.Promise((resolve, reject) => { $.ajax({ context: {test: 1}, // this type: "GET", url: "

箭头函数是否可以重新定义现有函数的行为?使用jQuery的get(是的,我知道)-我得到了两个不同的内部成功值,这取决于是否使用了arrow函数。有人能解释为什么会这样吗

var get = (e) => {
    return new window.Promise((resolve, reject) => {
      $.ajax({
        context: {test: 1}, // this
        type: "GET",
        url: "...",
        complete: function () {
          // this is only correct when using old syntax, arrow
          // function would redefine the value of this to the function's parent
        },
        complete: ()=>{ } // Is not working, this is not what I'd expect.
      });
    });
引入箭头函数主要是为了更改
this
的范围,这有助于避免一直使用
.bind(this)
。很自然,你会得到不同的价值观

箭头函数表达式的语法比函数表达式短,不绑定自己的this、arguments、super或new.target

更简洁、更简洁的语法是次要的。它们当然不是
功能的绝对替代品



现在,这已经从等式中去掉了-在您的示例中还有2个
oncomplete
回调。

完全正确。同样,你不能盲目地将每个
换成
循环换成
数组。对于每一个
,箭头函数都不应该是外观更好的函数语法的一部分。对箭头函数进行5分钟的研究可以相当直截了当地解释箭头函数是什么