简体   繁体   English

闭包中的箭头函数

[英]Arrow functions in closures

Why this is working:为什么这是有效的:

var a = () => { 

    var print = function(i) { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}

a().print(5).print2(5);

this is also working:这也有效:

var b = () => { 

    var print = (i) => { console.log(i); return this; }    
    return { print:print}
}
b().print('Arrow function works');

while this is not working:虽然这不起作用:

var b = () => { 

    var print = (i) => { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}
b().print(5).print2(5);

https://jsfiddle.net/Imabot/1gt2kxfh/14/ https://jsfiddle.net/Imabot/1gt2kxfh/14/

It's all due to arrow functions behavior( docs )这完全是由于箭头函数行为( 文档

Step by step explanation:分步说明:

 var b = () => { // 1 var print = (i) => { console.log(i); return this; } var print2 = function(i) { console.log(i); return this; } return { print:print , print2:print2 } } const res = b() // 2 const secondRes = res.print(5) // 3 secondRes.print2(5);

  1. here print function saves this reference from the outer scope, so this can't be reassigned anymore这里print功能保存this从外范围引用,所以this不能再重新分配
  2. now print function is not using this reference that comes from res variable, because this has already been attached to print function above现在print函数没有使用来自res变量的this引用,因为this已经附加到上面的print函数
  3. as a result secondRes is not going to reference to the object that was returned by b function.结果secondRes不会引用由b函数返回的对象。 But it will use this reference that is attached to print function.但它将使用附加到print功能的this引用。 And finally because secondRes doesn't have print2 property - it throws最后因为secondRes没有print2属性 - 它抛出

Hope it helps <3希望有帮助 <3

In a non-arrow function, the value of this depends on how the function is called.在非箭头函数中, this的值取决于函数的调用方式。 If the function is called as a member of an object, this refers to this object:如果函数作为对象的成员被调用,则this指的是这个对象:

someObj.myFunction() // inside myFunction this will point to someObj

In contrast, the arrow functions do not affect this .相反,箭头函数不影响this So whithin an arrow function the value of this is whatever it is in the enclosing scope.因此,在箭头函数中, this的值是封闭范围内的任何值。

The answer from Lex82 gives the why.来自Lex82的答案给出了原因。 If you want to return the functions, so you can use function chaining:如果要返回函数,则可以使用函数链接:

 var b = () => { var print = (i) => { console.log(i); return { print:print , print2:print2 }; } var print2 = function(i) { console.log(i); return this; } return { print:print , print2:print2 } } b().print(5).print2(5);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM