arrow function and bind
Can you bind arrow functions?
https://stackoverflow.com/questions/33308121/can-you-bind-arrow-functions
You cannot "rebind" an arrow function. It will always be called with the context in which it was defined. Just use a normal function.
From the ECMAScript 2015 Spec:
Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.
箭头函数中的this与词法域绑定, 即使使用bind企图改变this,也是徒劳的。
To be complete, you can re-bind arrow functions, you just can't change the meaning of
this
.
bind
still has value for function arguments:
((a, b, c) => { console.info(a, b, c) // 1, 2, 3 }).bind(undefined, 1, 2, 3)()
Try it here: http://jsbin.com/motihanopi/edit?js,console
箭头函数this确定, 普通函数中的this,由调用场景/对象确定。
如果也想模拟arrow函数效果, 可以使用bind接口,在定义的时候, 就把this绑定到词法中的this:
function (){
}.bind(this)
箭头函数不该使用场景
https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/
Defining methods on an object
Callback functions with dynamic context
Invoking constructors
Too short syntax
箭头函数该使用场景
函数短小
函数式计算的入参
需要确定this为词法域的
https://www.imooc.com/article/20607
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)