简体   繁体   English

请说明如何使此高阶函数起作用

[英]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. 我试图了解enhancershigh 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传递给增强器,这就是为什么我可能没有得到想要的行为的原因。

  • 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? 如何在定义后使用登录方法正确增强原始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()来查看结果。

user loggedInUser.login() instead of loggedInUser().login() , 用户loggingInUser.login()而不是loggingInUser()。login()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 请向我解释此高阶函数javascript代码 - Please explain me this higher-order function javascript code 有人可以解释这个高阶 JavaScript 函数令人困惑的语法吗? - Can someone explain this higher-order JavaScript function confusing syntax? 有人可以解释一下这个功能是如何工作的吗? - Can someone please explain how this function works? 这个高阶 function 在 JavaScript 中是如何工作的呢? - How does this higher order function work in JavaScript? 如何使没有返回值的回调在高阶函数中起作用 - How to make a callback without return value work within higher order function 我是jquery的新手,正在学习snap.svg,不知道这段代码如何工作? 有人可以解释一下该函数如何获取值吗? - I'm new to jquery and learning snap.svg and don't kow how this code work? Can someone Please explain how the function is getting values? 请任何人都可以解释这个 React 代码,工作如何? - Please anyone can explain this React code, how is work? 无法获得高阶功能而无法正常工作 - Can't get higher order function find to work 如何使 Aux 在反应中工作(高阶组件) - How to make Aux work in react (Higher order component) 我可以在 TypeScript 中表达这个高阶 function 签名吗? - Can I express this higher-order function signature in TypeScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM