在JavaScript中实现一次性函数 [英] Implementing a 'once' function in JavaScript

查看:283
本文介绍了在JavaScript中实现一次性函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个规范从Jasmine.js测试一次函数。我不知道如何实现这样的函数。

I have this spec from Jasmine.js which tests a once function. I'm not sure how to implement such a function though.

/* Functions that decorate other functions.  These functions return a version of the function
   with some changed behavior. */

// Given a function, return a new function will only run once, no matter how many times it's called
describe("once", function() {
  it("should only increment num one time", function() {
    var num = 0;
    var increment = once(function() {
      num++;
    });
    increment();
    increment();

    expect(num).toEqual(1);
  });
});

我不太明白我该怎么做。我知道我应该做一个函数(myFunction){}但除此之外,我被卡住了。

I don't quite understand what should I do here. I know I should make a function once(myFunction) {} but other than that, I am stuck. I figure out this has something to do with closures, still can't my head around it.

推荐答案

从UnderscoreJS源代码复制:

Copied from the UnderscoreJS source:

  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };

http://underscorejs.org/docs/underscore.html

这篇关于在JavaScript中实现一次性函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆