简体   繁体   中英

Assign a function return value to a variable in javascript

I have created a function that returns a variable.

function randomZone(){
  return x;
}

I want y to equal the function return value such that y=x;

y=randomZone();

I've read that this sets the variable equal to the function instead and that I have to put (); at the end of the function to invoke it first. Which way is correct?

y=randomZone()();
y=(randomZone())();

Also, how would you call it when you are invoking inside of another function? For example:

document.getElementById(randomZone()).classList.add('someClass');
document.getElementById(randomZone()()).classList.add('someClass');
document.getElementById((randomZone())()).classList.add('someClass');
document.getElementById((randomZone())();).classList.add('someClass');

Which way is correct? Wouldn't you also not include the semi-colon because that would terminate the code early?

  • y=randomZone; assigns the function itself to the variable y , now you can call the function by doing y()
  • y=randomZone(); assigns the return of the function to y , now y is equals to x (the return of the function) when this code is executed by any other script
  • and using an IIFE you can do eny of this instantly when the script is loaded:

( function() { y=randomZone(); //code inside these brackets is executed instantly } ());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM