+ 7
How to make a variable in function() goes public?
Note: Without Declaring a variable outside the function() first
22 Respuestas
+ 9
function foo()
{
window.bar = 3.1415;
}
console.log(bar); // undefined
foo();
console.log(bar); // 3.1415
+ 5
Jingga Sona 🐺 If your goal is not pullulate global namespace, you can use a single object containing all your "module global" vars or put all inside an anonymous function
+ 5
Jingga Sona 🐺 See here
https://code.sololearn.com/W2W90m2IVf0a/?ref=app
Maybe it can be useful to you
+ 5
Jingga Sona 🐺 I think that you have to read how define an object with constructor... Classic example is:
function Person(name, surname){
this.name= name
this.surname= surname
this.printMe= function(){
alert(this.name +' '+ this.surname);
}
}
var me= new Person('KrOW', 'Black')
me.printMe()
This is only the point of the "iceberg"
+ 4
Jingga Sona 🐺 I mean why you asked it? You have a practical problem to solve in that way or is just your curiosity?
+ 4
I think that Jingga Sona 🐺 want follow common suggestion to not "fill" the global namespace... With large codes can be useful but i dont know if this is him final goal
+ 4
Jingga Sona 🐺 I highly suggest you to follow this guide https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects
+ 4
Thanks KrOW !👍
+ 4
👍👍👍👍
+ 4
neo.h This is a simple example, which make no difference from direct return a value. Closure is more applicable if we need to do encapsulation, and return only the required object.
+ 3
Jingga Sona 🐺 Just for curiosity: Why?
+ 3
Thanks! Can you explain it?
+ 3
KrOW well, i am trying to make a small library called shortcut.js, and i want to include canvas basic program so it save times
+ 3
I did not learn anonymous function yet😅
+ 3
He wants to avoid declaring the variable outside, but yeah, I think the same
+ 3
I have done the same before, but I stuffed all my functions inside an object
KrOW I cant speak for him. But I made something similar, to simply getting the context, resizing, clipping and drawing custom shapes. It's not a great deal but it's quite handy.
+ 3
Use closure
var goo = function foo()
{
var bar = 3.1415;
return {bar};
}().bar;
console.log(goo); // 3.1415
https://code.sololearn.com/WXPFenTEzB6v/?ref=app
+ 3
U could also assign a variable without let, const or var. Just variable = 5
+ 2
+ 2
Calviղ How's that different from a normal return?