gpt4 book ai didi

javascript - 闭包中的箭头函数

转载 作者:行者123 更新时间:2023-12-03 17:21:28 26 4
gpt4 key购买 nike

为什么这有效:

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);

这也有效:

var b = () => { 

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

虽然这不起作用:

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/

最佳答案

这都是由于箭头函数的行为( docs )

分步说明:

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. 此处 print 函数保存来自外部作用域的 this 引用,因此 this 无法再重新分配
  2. 现在 print 函数未使用来自 res 变量的 this 引用,因为 this 已经附加到上面的 print 函数
  3. 因此,secondRes 不会引用 b 函数返回的对象。但它将使用附加到 print 函数的 this 引用。最后,因为 secondRes 没有 print2 属性 - 它会抛出

希望对你有帮助<3

关于javascript - 闭包中的箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59911385/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com