How to make a function global?
See original GitHub issueThe question title is a bit weird, but I’m going to explain it anyway 😃
Normally, in NodeJS or in a browser, when you store a variable or function on the global or window object it will be globally available in all scripts (without using window. or global. qualifiers), right? How can this be done in duktape? I already created a global object, but don’t know how to continue.
Maybe I’m misunderstanding something here, so let me quickly explain what I’m actually trying to do: my app can now load the Jasmine test framework node module, which defines some functions like describe() or it(), just like Mocha does. You can usually just call them without a need to “require” something or have an object to call things on. However, in my test spec files I get an error that describe is unknown. So I wonder what could be wrong here? The frameworks seems to load fine (no errors and I get output from it).
The call stack is:
Could not load main script: main.js
ReferenceError: identifier 'describe' undefined
at main (<path>/tests/self-tests/path-test.js:4)
at require () native
at forEach () native
at runtTests (main.js:26)
at global (main.js:35)
at [anon] (node_modules/jasmine/lib/jasmine.js:198)
at [anon] (eval:1)
and path-test.js contains:
"use strict"
describe("Blah", function() {
it("Do it", function() {
print("testing");
});
});
Issue Analytics
- State:
- Created 6 years ago
- Comments:15 (10 by maintainers)

Top Related StackOverflow Question
I’m assuming you want to do this from Ecmascript (not C) code.
If a script just writes:
it will establish a global “foo” property (assuming no shadowing variable exists) from either program code, eval code, or even function code (which includes modules). If you say:
a global variable is established if the statement is executed as program code or eval code in the global context. In a function it establishes a local variable.
You can gain access to the global object from any scope as follows:
That looks a bit weird, but what it does is: (1) create a non-strict function that returns its “this” binding, and (2) call the function. The call uses “undefined” for the “this” binding, but because the function is not strict, it gets coerced to the global object (which is standard ES “this” binding handling) for the call. The return value is thus always the global object, regardless of where the idiom occurs.
In other words, if one does this:
That should print 812. The
globalreference is no different.