Passing a parameter to a close function in javascript

MyLibrary.MyModule = ( function initialise() { this.id = id; this.c = document.getElementById(id); this.ctx = this.c.getContext('2d'); this.properties = { setup: { backgroundColour: options.setup.backgroundColour || 'black' }, scale: { show: options.scale.show || true, colour: options.scale.color || 'white' }, } console.log(properties.setup.baseFontSize); } )(id, options); 

I call this code with

 new MyLibrary.MyModule('c',options); 

but the "id" and parameters do not seem to be defined.
can someone help?

+6
javascript closures javascript-objects
source share
3 answers

Your MyLibrary.MyModule itself is undefined . This is because you are calling an anonymous function with no return value for its purpose.

I assume you wanted to do this instead:

 MyLibrary.MyModule = function initialise(id, options) { this.id = id; this.c = document.getElementById(id); this.ctx = this.c.getContext('2d'); this.properties = { setup: { backgroundColour: options.setup.backgroundColour || 'black' }, scale: { show: options.scale.show || true, colour: options.scale.color || 'white' }, } console.log(properties.setup.baseFontSize); }; 

Now you can do:

 var inst = new MyLibrary.MyModule('c',options); 

... and 'c' and options will be received as arguments to the constructor.

If your goal for an expression called by a directly called function was to close some default value that might be referenced by the constructor, then IIFE would have to return a function that refers to that value.

+5
source share

As written, I do not think that I will do something like what you want. You initialize "MyLibrary.MyModule" with basically nothing; there is no return value from this "initialize" function, and you call it as if it had it.

I can’t say what you are trying to do, but:

 MyLibrary.MyModule = (function whatever() { /* ... */ })(id, options); 

means: "call the function by anyone, using the argument list, consisting of the values ​​of the variable" id "and variables" options ", and then set the property" MyModule "to the object referenced by" MyLibrary ", any value is returned from this function call.

When the smoke clears, "MyLibrary.MyModule" will not be a function, as far as I can tell. Perhaps if you explain what you want, it means that someone can help fix it.

+4
source share

You want something like this:

 MyLibrary.MyModule = function(id, options) { this.id = id; this.c = document.getElementById(id); this.ctx = this.c.getContext('2d'); this.properties = { setup: { backgroundColour: options.setup.backgroundColour || 'black' }, scale: { show: options.scale.show || true, colour: options.scale.color || 'white' }, } }; 
0
source share

All Articles