How can you pass arguments to a function when implementing the Revealing module pattern in JavaScript. I have a module like this
var GlobalModule = (function() {
function consoleLog(textToOutput) {
console.log(textToOutput);
}
return {
consoleLog: consoleLog()
};
})();
Later on, when i run GlobalModule.consoleLog("Dummy text");, I get undefined as the output.
return {
consoleLog: consoleLog()
};
That part of your code is wrong.
You're exporting the Result of the consoleLog call due to the () at the end of the function, where you want to export the function itsself.
So just remove the function call:
return {
consoleLog: consoleLog
};
Do with function inside the return object
var GlobalModule = (function() {
return {
consoleLog: function(textToOutput)
{
console.log(textToOutput);
}
}
})();
GlobalModule.consoleLog("Dummy text");
Simply Do like this same output achieved . object => function call .No need a return object
var GlobalModule ={
consoleLog: function(textToOutput) {
console.log(textToOutput);
}
}
GlobalModule.consoleLog("Dummy text");
Change the line
consoleLog: consoleLog()
To
consoleLog: consoleLog
Or even(es6) to:
consoleLog
You can do like this
var GlobalModule = (function() {
function consoleLog(textToOutput) {
console.log(textToOutput);
}
return {
consoleLog: consoleLog // () is removed otherwise it will execute immediately
};
})();
GlobalModule.consoleLog('Hello')
DEMO
You you want to pass a global variable pass it in the parenthesis of the IIFE
var GlobalModule = (function(x) {
function consoleLog(textToOutput) {
console.log(textToOutput,x); // will log Hello temp
}
return {
consoleLog: consoleLog
};
})('temp');
Related
Pulling my hair out here trying to understand the infuriating nuances of Javascript. Hopefully some JS guru can take a gander, point and go, "well, there's yer problem...".
Here's a slimmed down sample of the problem:
var Parent = (function () {
var func1 = function () {
func2(function (res) {
console.log(res);
});
};
var func2 = function (callback) {
callback('abc');
};
return {
init: function () {
func1();
func2();
}
};
})();
Call with Parent.init();
This fails with the error:
Uncaught TypeError: callback is not a function
at check2 (<anonymous>:9:9)
at Object.init (<anonymous>:15:13)
at <anonymous>:1:8
What's getting me, is that if I comment out the enclosing code, like so, then it works as expected:
// var Parent = (function () {
var func1 = function () {
func2(function (res) {
console.log(res);
});
};
var func2 = function (callback) {
callback('abc');
};
// return {
// init: function () {
// func1();
// func2();
// }
// };
// })();
...and call with func1();
Result:
abc
What am I missing?
Thanks
In your version, you're calling func2() without specifying the callback function, which is a required argument. In your second example (with init commented out), you're correctly specifying the callback function in func2(function (res) { ... });.
Is the below snippet something you're looking for?
const Parent = (function () {
const func1 = function () {
func2(function (res) {
console.log(res);
});
}
const func2 = function (callback) {
callback('abc'); // this is passing 'abc' to line 3 of this snippet
}
return {
init: function () {
func1();
// func2(); // you don't want to call "func2" here, as "func1" calls it
// Or you could run:
func2(function (res) {
console.log(res);
});
// But this makes "func1" redundant
}
};
});
Parent().init();
// Output
abc
You have to pass callback parameter into func2 inside init. something like this.
init: function () {
func1();
func2(function (res) {
console.log(res);
});
}
From a comment on the question:
I just want to know why it works in the one sample, but not the other.
Because in one example you pass an argument to func2 and in the other you don't. Look at the working version:
func2(function (res) {
console.log(res);
});
vs. the non-working version:
func2();
The difference is that the first one passes a function which gets invoked as callback('abc'); whereas the second one passes nothing, so the attempt to invoke the non-existant callback function fails.
As an aside, in your non-working example you call func2 twice, once with the callback and once without. So it both "works" and "fails" in that case.
It's redundant but I am learning JS and I want to know how it really works.
Returning a function directly from a module
let func1 = function () {
let test = function () {
console.log("1");
}
return {
getTest : test
}
}
Returning a function by using a function
let func1 = function () {
let test = function () {
console.log("1");
}
return {
getTest : function () {
return test;
}
}
}
In the first case, the getTest property of your object points to a function, so calling it this way:
func1().getTest()
Should result in logging 1.
In the second case, getTest returns a function which returns another function, so you'd have to also call the result in order to get 1, this way:
func1().getTest()();
Calling just getTest will return your function object, rather than calling it.
So I have a function like
func()
{
const curVal = this.curVal;
const callAgain = () => { func(); };
Axios.get('somecontroller/someaction')
.then(response =>
{
const newVal = response.data.curVal;
if(curVal === newVal)
setTimeout(callAgain, 500);
else
// ....
})
.catch(response =>
{
// ...
});
}
and my browser is complaining about the line
const callAgain = () => { func(); };
saying that func is undefined. Any idea why? How can I fix?
You cannot define a function the way you posted.
However, you can for example use the function keyword to define your function:
function func() {
...
}
func(); // it works!
Edit:
According to your comment, this is a object method declaration. In order to make this work, you first need to make sure your browser supports this particular ES2015 feature or if not, you transpile it to valid ES5.
Then you should be able to access the function using this.func():
const callAgain = () => { this.func(); };
In case you are using func() e.g. as a callback for a DOM event, you also have to make sure that this is bound correctly in func, for example by explicitly binding it in the constructor:
constructor() {
...
this.func = this.func.bind(this);
}
Define the function using either of the following:
function func(){ ... }
Or...
var func = function(){ ... }
When you define it like this:
func() { ... }
JavaScript thinks you're trying to execute an existing function called func, and then run the block of code { ... }
I presume it is possible to create a JavaScript function that disables it self after it is done running.
Is possible? How can this effect be achieved?
Wrap arbitrary runnable in following manner:
function once(subject) {
var first = true;
return function() {
if (first) {
first = false;
return subject();
} else {
return null;
}
};
}
var wrapper = once(function() {alert("No more!");});
wrapper(); // alerts
wrapper(); // noop
Runnable will only be executed on first invocation of wrapper.
You can convert a function of arbitrary arguments to an argumentless runnable.
If you want the functionality to be happen only once you can use the following function
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
Courtesy: https://davidwalsh.name/essential-javascript-functions
something like this?
function a(){ alert(1); a = null;}
invoke a() once, second time it will say
Uncaught TypeError: a is not a function
if the function is anonymous, then make it IIFE
(function(){ alert(1);})();
var _flag = true; // Have a flag variable.
function oneTimer(){
// Check flag is set to true or not
if(!_flag) return;
_flag = false;
// Your function definition here.
}
As commented, if you want to execute a function only once, you should try IIFE. These functions are invoked immediately and cannot be called afterwards.
Following is a sample code.
(function test() {
console.log("test");
(function innerFunc() {
console.log("Inner Function");
})();
try {
innerFunc();
} catch (ex) {
console.log(ex)
}
})();
try {
test();
} catch (ex) {
console.log(ex)
}
Pretty easy, just assign an empty function to the function:
function once() {
alert('once');
once = function () { };
}
once();
once();
I am trying to achieve something like the following but dont know whats wrong:
$.a = function() {
// some logic here
function abc(id) {
alert('test'+id);
}
}
$.a.abc('1');
I tried using the return function, but that doesnt seem to work either. Can someone please help.
Thank you for your time.
Since $.a must be a function in itself, you'll have to add the abc function as a property to the $.a function:
$.a = function () {
// some logic here...
};
$.a.abc = function (id) {
alert('test' + id);
};
If abc must be defined from within the $.a function, you can do the following. Do note that $.a.abc will not be available until $.a has been called when using this method! Nothing inside a function is evaluated until a function is called.
$.a = function () {
// Do some logic here...
// Add abc as a property to the currently calling function ($.a)
arguments.callee.abc = function (id) {
alert('test' + id);
};
};
$.a();
$.a.abc('1');
$.a = (function(){
var a = function() {
//...
};
a.abc = function() {
//...
}
return a;
})();