[英]Please explain how I can make this higher order function work
I am trying to understand how enhancers
or high order functions
work in JavaScript and how I can compose functions to deliver a decorated functionality. 我试图了解enhancers
或high order functions
如何在JavaScript中工作,以及如何组合函数以提供修饰的功能。
So I have a basic user
factory function: 所以我有一个基本的user
工厂功能:
function user() {
return {
name: 'amit',
age: 41
}
}
Now I want add authentication behavior like a mock login
method to this factory. 现在,我想向该工厂添加身份验证行为,例如模拟login
方法。 So I write this enhancer 所以我写了这个增强器
function authUser(fn) {
fn.login = () => {
return 'you are now logged in'
}
return fn
}
Now I pass user
into this enhancer 现在,我将user
传递到此增强器中
let loggedInUser = authUser(user)
But when I try to call the login
method like this... 但是当我尝试像这样调用login
方法时...
loggedInUser().login()
I get 我懂了
Uncaught TypeError: loggedInUser(...).login is not a function
I understand that I am not really calling the fn being passed into the enhancer and that is why probably I am not getting the behavior I want. 我知道我并不是真正地将fn传递给增强器,这就是为什么我可能没有得到想要的行为的原因。
user
object with a login method or add more properties to it after definition? 如何在定义后使用登录方法正确增强原始user
对象或向其添加更多属性? It's because you're actually assigning login
property to function fn
, not the returned value of fn
. 这是因为你实际上指定login
属性的功能fn
,而不是返回值fn
。 You can try calling loggedInUser.login()
instead of loggedInUser().login()
to see the result. 您可以尝试调用loggedInUser.login()
而不是loggedInUser().login()
来查看结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.