简体   繁体   中英

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.

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.

  • But where do I call it? and
  • how do I correctly enhance the original 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.

user loggedInUser.login() instead of loggedInUser().login() ,

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM