简体   繁体   中英

CommonJS & functions

I'm using Backdraft loader which follows CommonJS standard. 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. Does define() do a closure automatically or what's going on?

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. It's about the CJS module definition.

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. So each time you call that function. It returns the same value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM