I want to make the whole function a variable and use it in other functions like something below:
var a = (function() {
var x = '5';
b(x);
})();
function b(i) {
this.i = i;
// console.log(i); // 5
return i;
}
var c = function() {
console.log(b);
}
var button = document.getElementById('button');
button.addEventListener("click", c, false);
How do I display b as 5 instead of function code.
Thank you,
You can’t. In JavaScript you execute a function with brackets()
Thanks for response. Is there any other way around I can achieve this?
I can’t understand your question.
Functions in JavaScript can be passed around just like any other variable - just leave the () off the end as that runs the function rather than just referencing it.
Sorry for my bad English. In a real practice, I extract a variable from function a. It’s a multiple-nested function. So, I store the value of the variable in a function to be further use it. Now that I want to use that value in another function.
I can’t extract that value from that function and try to figure it out.
Hope that’s clear. Thanks
For passing variables between functions you have three choices.
- Define the variable outside of both functions.
- Return the variable from the first function so you can pass it to the second
- Make both functions methods of the same object and define the variable as a property of that object.
Thank you,
I make it a global variable. So it can be access from anywhere. I know it’s bad practice but I can get my job done.