[英]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);
print
function saves this
reference from the outer scope, so this
can't be reassigned anymoreprint
功能保存this
从外范围引用,所以this
不能再重新分配print
function is not using this
reference that comes from res
variable, because this
has already been attached to print
function aboveprint
函数没有使用来自res
变量的this
引用,因为this
已经附加到上面的print
函数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 throwssecondRes
没有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.