JavaScript Module Pattern across multiple files - closures

I'm having to restructure some ancient code, and there's quite a bit of it in lots of different files. The approach is to use the revealing module pattern, as described in JavaScript Module Pattern: In-Depth (section Cross-File Private State).
The first function expression works great, and I can see in Firebug that the function components are also assigned correctly in the second block. But then the variable suddenly ends up undefined.
I put together a simplified example, and the console shows the variable is undefined after the second assignment.
var test = (function ($, ns, undefined)
{
function test1()
{
console.log("executing test1");
ns.testx.test2();
}
return { test1: test1 };
}(jQuery, test || {}));
console.log(test);
var test = (function ($, ns, undefined)
{
ns.testx = (function ()
{
function test2()
{
console.log("executing test2");
}
return { test2: test2 }
})();
}(jQuery, test || {}));
console.log(test);
// DOM ready
$(function ()
{
test.test1();
});
Several variations, such as defining the variable just once at the top don't work either. If the two function expressions are swapped, test 1 is executed but ns.testx is undefined.
I fear I'm missing the blindingly obvious and would really like to understand why this does not work. I also need to get it to work, so any help is greatly appreciated (merging the files into one is not an option).

Try
var test = (function ($, ns, undefined)
{
function test1()
{
console.log("executing test1");
ns.testx.test2();
}
ns.test1 = test1;
return ns;
}(jQuery, test || {}));
console.log(test);
var test = (function ($, ns, undefined)
{
ns.testx = (function ()
{
function test2()
{
console.log("executing test2");
}
return { test2: test2 }
})();
return ns;
/*
This will be
{
test1: test1,
testx: {
test2: test2
}
}
*/
}(jQuery, test || {}));

Related

type safe create Lua tables in Haxe without runtime overhead and without boilerplate

I am trying to write some externs to some Lua libraries that require to pass dictionary tables and I want to make them type safe.
So far, I have been declaring abstract classes with public inline constructors, but this gets tedious really fast:
abstract JobOpts(Table<String, Dynamic>) {
public inline function new(command:String, args:Array<String>) {
this = Table.create(null, {
command: command,
arguments: Table.create(args)
});
}
}
Is there a better way that allows me to keep things properly typed but that does not require that much boilerplate?
Please note that typedefs and anonymous structures are not valid options, because they introduce nasty fields in the created table and also do a function execution to assign a metatable to them:
--typedef X = {cmd: String}
_hx_o({__fields__={cmd=true},cmd="Yo"})
My abstract code example compiles to a clean lua table, but it is a lot of boilerplate
Some targets support #:nativeGen to strip Haxe-specific metadata from objects, but this does not seem to be the case for typedefs on Lua target. Fortunately, Haxe has a robust macro system so you can make the code write itself. Say,
Test.hx:
import lua.Table;
class Test {
public static function main() {
var q = new JobOpts("cmd", ["a", "b"]);
Sys.println(q);
}
}
#:build(TableBuilder.build())
abstract JobOpts(Table<String, Dynamic>) {
extern public inline function new(command:String, args:Array<String>) this = throw "no macro!";
}
TableBuilder.hx:
import haxe.macro.Context;
import haxe.macro.Expr;
class TableBuilder {
public static macro function build():Array<Field> {
var fields = Context.getBuildFields();
for (field in fields) {
if (field.name != "_new") continue; // look for new()
var f = switch (field.kind) { // ... that's a function
case FFun(_f): _f;
default: continue;
}
// abstract "constructors" transform `this = val;`
// into `{ var this; this = val; return this; }`
var val = switch (f.expr.expr) {
case EBlock([_decl, macro this = $x, _ret]): x;
default: continue;
}
//
var objFields:Array<ObjectField> = [];
for (arg in f.args) {
var expr = macro $i{arg.name};
if (arg.type.match(TPath({ name: "Array", pack: [] } ))) {
// if the argument's an array, make an unwrapper for it
expr = macro lua.Table.create($expr, null);
}
objFields.push({ field: arg.name, expr: expr });
}
var objExpr:Expr = { expr: EObjectDecl(objFields), pos: Context.currentPos() };
val.expr = (macro lua.Table.create(null, $objExpr)).expr;
}
return fields;
}
}
And thus...
Test.main = function()
local this1 = ({command = "cmd", args = ({"a","b"})});
local q = this1;
_G.print(Std.string(q));
end
Do note, however, that Table.create is a bit of a risky function - you will only be able to pass in array literals, not variables containing arrays. This can be remedied by making a separate "constructor" function with the same logic but without array➜Table.create unwrapping.

Whats the difference about defining a variable as Function or Function() in dart

What's the diference about setting the type of a variable as Function or Function()?
Function function1 = () { print("1"); };
Function() function2 = () { print("2"); };
// Both works
function1();
function2();
The type Function does just say that your variable points to a Function but does not require this variable to point to a function with a specific signature.
Function() actually gives an analyzer warning on my machine because this is not entirely correct. Instead it should have been void Function() function2 = () { print("2"); };. This specifies that function2 must point to a function which does not return anything and takes zero arguments.
The last is also what would be declared by Dart itself if you have used var or final instead of specifying the type.
The difference becomes clear if you change the method to take an argument:
Function function1 = (int a) { print("1"); }; // works
void Function() function2 = (int a) { print("2"); }; // error

Using "IIFE" to create private scope; do I need parentheses?

This is my code:
var badget = function () {
var privetVar = 23;
var privetFunc = function (a) {
return privetVar + a;
}
return {
publicFunc: function (b) {
console.log(privetFunc (b));
}
}
}();
It works well; I have access to the publicFunc() using badget.publicFunc(), which has access to the privetVar and privetFunc() due to "closures".
However, someone told me I must use parentheses like this:
var badget = (function() {
var privetVar = 23;
var privetFunc = function(a) {
return privetVar + a;
}
return {
publicFunc: function(b) {
console.log(privetFunc(b));
}
}
})();
Is this second example considered a preferable syntax?
No, the parentheses are not required in this example. Typically people don't use the return value of an IIFE, so the parentheses are required to differentiate a function expression from a function statement.
Since your function declaration in your first example is already part of an assignment expression, it's already a function expression, so the parentheses aren't required.
TL;DR
Valid
var badget = function () {
...
}();
(function () {
...
})();
(function () {
...
}());
Valid (but not necessary)
var badget = (function () {
...
})();
var badget = (function () {
...
}());
Invalid (function statements cannot be IIFEs)
function () {
...
}();

Javascript Module pattern and closures

I'm trying to get my head around the module pattern in Javascript and have come across various different ways that I can see to do it. What is the difference (if any) between the following:
Person = function() {
return {
//...
}
};
person1 = Person();
function Person2() {
return {
//...
}
}
person2 = Person2();
person3 = function() {
return {
//...
}
}();
person4 = (function() {
return {
// ...
}
})();
person5 = (function() {
return {
// ...
}
}());
They all seem to do the same thing to me.
// This creates a function, which then returns an object.
// Person1 isn't available until the assignment block runs.
Person = function() {
return {
//...
}
};
person1 = Person();
// Same thing, different way of phrasing it.
// There are sometimes advantages of the
// two methods, but in this context they are the same.
// Person2 is available at compile time.
function Person2() {
return {
//...
}
}
person2 = Person2();
// This is identical to 'person4'
// In *this* context, the parens aren't needed
// but serve as a tool for whoever reads the code.
// (In other contexts you do need them.)
person3 = function() {
return {
//...
}
}();
// This is a short cut to create a function and then execute it,
// removing the need for a temporary variable.
// This is called the IIFE (Immediate Invoked Function Expression)
person4 = (function() {
return {
// ...
}
})();
// Exactly the same as Person3 and Person4 -- Explained below.
person5 = (function() {
return {
// ...
}
}());
In the contexts above,
= function() {}();
= (function() {}());
= (function() {})();
All do exactly the same thing.
I'll break them down.
function() {}();
<functionExpression>(); // Call a function expression.
(<functionExpression>()); // Wrapping it up in extra parens means nothing.
// Nothing more than saying (((1))) + (((2)))
(<functionExpression>)();
// We already know the extra parens means nothing, so remove them and you get
<functionExpression>(); // Which is the same as case1
Now, all of that said == why do you sometimes need parens?
Because this is a *function statement)
function test() {};
In order to make a function expression, you need some kind of operator before it.
(function test() {})
!function test() {}
+function test() {}
all work.
By standardizing on the parens, we are able to:
Return a value out of the IIFE
Use a consistent way to let the reader of the code know it is an IIFE, not a regular function.
The first two aren't a module pattern, but a factory function - there is a Person "constructor" that can be invoked multiple times. For the semantic difference see var functionName = function() {} vs function functionName() {}.
The other three are IIFEs, which all do exactly the same thing. For the syntax differences, see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.
I've found a extremely detail page explaining this kind of stuff
Sth called IIFE
Hope will help.

Assign function/method to variable in Dart

Does Dart support the concept of variable functions/methods? So to call a method by its name stored in a variable.
For example in PHP this can be done not only for methods:
// With functions...
function foo()
{
echo 'Running foo...';
}
$function = 'foo';
$function();
// With classes...
public static function factory($view)
{
$class = 'View_' . ucfirst($view);
return new $class();
}
I did not found it in the language tour or API. Are others ways to do something like this?
To store the name of a function in variable and call it later you will have to wait until reflection arrives in Dart (or get creative with noSuchMethod). You can however store functions directly in variables like in JavaScript
main() {
var f = (String s) => print(s);
f("hello world");
}
and even inline them, which come in handy if you are doing recusion:
main() {
g(int i) {
if(i > 0) {
print("$i is larger than zero");
g(i-1);
} else {
print("zero or negative");
}
}
g(10);
}
The functions stored can then be passed around to other functions
main() {
var function;
function = (String s) => print(s);
doWork(function);
}
doWork(f(String s)) {
f("hello world");
}
I may not be the best explainer but you may consider this example to have a wider scope of the assigning functions to a variable and also using a closure function as a parameter of a function.
void main() {
// a closure function assigned to a variable.
var fun = (int) => (int * 2);
// a variable which is assigned with the function which is written below
var newFuncResult = newFunc(9, fun);
print(x); // Output: 27
}
//Below is a function with two parameter (1st one as int) (2nd as a closure function)
int newFunc(int a, fun) {
int x = a;
int y = fun(x);
return x + y;
}

Resources