[go: up one dir, main page]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个 once 函数,记忆返回结果只执行一次【热度: 319】 #987

Open
yanlele opened this issue Oct 12, 2024 · 0 comments
Labels
JavaScript JavaScript 语法部分
Milestone

Comments

@yanlele
Copy link
Member
yanlele commented Oct 12, 2024

关键词:once 函数

以下是使用 JavaScript 实现一个once函数的方法:

function once(func) {
  let hasRun = false;
  let result;
  return function () {
    if (!hasRun) {
      result = func.apply(this, arguments);
      hasRun = true;
    }
    return result;
  };
}

你可以这样使用这个函数:

function expensiveOperation() {
  console.log("执行了昂贵的操作");
  return 42;
}

const memoizedOperation = once(expensiveOperation);

console.log(memoizedOperation()); // 执行了昂贵的操作,返回 42
console.log(memoizedOperation()); // 直接返回上次的结果 42,不再执行昂贵的操作

在这个实现中,once函数接收一个函数作为参数,并返回一个新的函数。新函数会记住第一次调用时的结果,后续调用直接返回这个结果,而不会再次执行传入的函数。

@yanlele yanlele added the JavaScript JavaScript 语法部分 label Oct 12, 2024
@yanlele yanlele added this to the milestone Oct 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语法部分
Projects
None yet
Development

No branches or pull requests

1 participant