[英]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 等于函数返回值,使得 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
,现在您可以通过执行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将函数的返回值分配给y
,现在当此代码由任何其他脚本执行时y
等于x
(函数的返回值) ( function() { y=randomZone(); //code inside these brackets is executed instantly } ());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.