它用于 _.once 下划线是什么? [英] what is it used for _.once in underscore?

查看:32
本文介绍了它用于 _.once 下划线是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 underscore.js 中查看了源代码的 once API,然后徘徊它是用来做什么的在方法中,它似乎什么都不做:

func = null

来源:

 _.once = function(func) {var 跑 = 假,备忘录;返回函数(){如果(跑)返回备忘录;跑 = 真;备忘录 = func.apply(this, arguments);功能 = 空;返回备忘录;};};

解决方案

该函数的作用可以在文档中找到:

<块引用>

创建只能调用一次的函数版本.重复调用修改后的函数将无效,返回原始调用的值.对初始化函数很有用,而不必设置布尔标志然后稍后检查.

在此提交消息中解释了为什么设置func = null::><块引用>

假设我们永远不会在 _.once() 上再次运行包装函数,我们可以将 null 分配给 func 变量,因此函数(及其所有继承的范围)可以在需要时由 GC 收集.

I just look at the once API of source in underscore.js, then wandering what is it the used for in the method, it seems doing nothing:

func = null

the 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;
    };
  };

解决方案

What the function does can be found in the documentation:

Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

Why set func = null is explained in this commit message:

Assuming we'll never run the wrapped function again on _.once(), we can assign null to the func variable, so function (and all its inherited scopes) may be collected by GC if needed.

这篇关于它用于 _.once 下划线是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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