[英]CommonJS & functions
I'm using Backdraft loader which follows CommonJS standard. 我正在使用遵循CommonJS标准的Backdraft加载程序。 I'm trying to understand how everything works but now I need some advice.
我正在尝试了解所有工作原理,但是现在我需要一些建议。
Let's say I want to get a timestamp and I do this: 假设我想获取一个时间戳,然后执行以下操作:
define(function(){
return (new Date()).getTime()
});
Then I do a simple require and try to run it: 然后,我做了一个简单的要求并尝试运行它:
require(['timestamp'],function(timestamp) {
console.log(timestamp())
console.log(timestamp())
console.log(timestamp())
}
Now what I get is the same timestamp 3 times from the point when timestamp function was evaluated. 现在我得到的是从评估时间戳功能起的3倍相同的时间戳。 Does define() do a closure automatically or what's going on?
define()是否自动执行关闭操作或发生了什么?
I'm learning functional programming so not understanding how to do these small functions that can be reused is kinda hampering my efforts :) 我正在学习函数式编程,所以不了解如何做这些可以重用的小函数,这有点妨碍了我的努力:)
It's not about Functionnal programming. 这与Functionnal编程无关。 It's about the CJS module definition.
关于CJS模块定义。
In the above example, after you require "timestamp" module, Backdraft loader(Suppose it works the same with RequireJS since I don't know Backdraft) will help to new timestamp and cache it. 在上面的示例中,在您需要“时间戳”模块之后,Backdraft加载器(假设它与RequireJS相同,因为我不知道Backdraft)将有助于创建新的时间戳并对其进行缓存。 So each time you call that function.
因此,每次调用该函数。 It returns the same value.
它返回相同的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.