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.
So I have a basic user
factory function:
function user() {
return {
name: 'amit',
age: 41
}
}
Now I want add authentication behavior like a mock login
method to this factory. 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
let loggedInUser = authUser(user)
But when I try to call the login
method like this...
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.
user
object with a login method or add more properties to it after definition? It's because you're actually assigning login
property to function fn
, not the returned value of fn
. You can try calling loggedInUser.login()
instead of loggedInUser().login()
to see the result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.