I came across this type function in an example code, and it looks widely used. But I cannot figure out how to call this, or infact, what pattern it represents.
l = function (a1){
someVar = {
someFn: function(a2){
console.log(a1);
console.log(a2);
}
}
}
How would i go about executing someFn? Does this have something to do with closures?
UPDATE:
This is how the code is being used. As @joseph-the-dreamer guessed, it is being used as part of a module, where:
App.module("Module", function(a1) {
someVar = {
someFn: function(a2){
console.log(a1);
console.log(a2);
}
}
})
From it's current state, you need to call l
first to set someVar
to access someFn
. Otherwise, you can't access someFn
at all.
But without any variable declaration of someVar
, calling l
will create an implied global someVar
. Implied globals isn't a good practice. You should declare someVar
somewhere, even if you mean it to be a global.
var someVar;
l = function (a1){
someVar = {
someFn: function(a2){
console.log(a1);
console.log(a2);
}
}
}
l(1);
someVar.someFn(2);
//1
//2
You can also return someVar
from calling l
to access someVar
. Note that this time, someVar
is a local variable in l
.
var l = function (a1){
var someVar = {
someFn: function(a2){
console.log(a1);
console.log(a2);
}
}
return someVar;
}
l(1).someFn(2);
As for pattern, I think what you have there is an incomplete form of the module pattern. Usually, module pattern wraps things in an IIFE, and returns an object as an interface to the module.
If someVar
is not a variable in a scope outside of l()
, then you cannot call someFn()
, since someFn()
is a private member function of someVar
.
Otherwise, if you do have access to someVar
, then you can call someFn()
like this someVar.someFn()
. Note that in this case, the console.log(a1)
will behave strangely since a1
is has been assigned only since the last time l()
was called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With