JavaScript: When assigning an anonymous function to a variable, function return value is not passed, rather the function as a string

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-07 03:28:56

问题


I am trying to learn JavaScript but I've come across a hurdle. If the answer is obvious and reachable through a simple search I apologize in advance. I am a novice to programming and JavaScript, and unsure what line of inquiry to follow.

In the following code, the function takes values from a HTML form, does some processing and sends them back. I've tested the input and output process and it's working correctly.

function foo() {

var x = parseInt(document.formdata.fieldone.value);
var y = parseFloat(document.formdata.fieldtwo.value);

if (isNaN(y))
    { var z = x; }
else
    { var z = function(x, y) {
            if ((y * (x / 100)) < 1) {
                return (x + Math.ceil(y * (x / 100))); }
            else if ((y * (x / 100)) > 1) {
                return (x + Math.round(y * (x / 100))); }
            else {
                return 0; } } }

var bar = document.getElementById("output");

bar.innerHTML = z; }

The problem is, when the else branch of the conditional statement tries to process the anonymous function, the return value isn't assigned; rather the entirety of the function as a string. That is, the following appears in the HTML page:

function (x, y) { if ((y * (x / 100)) < 1) { return (x + Math.ceil(y * (x / 100))); } else if ((y * (x / 100)) > 1) { return (x + Math.round(y * (x / 100))); } else { return 0; } }

I've tested the code in Chrome and Firefox and the result is the same.

Any help is appreciated and thank you in advance.


回答1:


You need to call the function by passing it two arguments, because otherwise the z variable will just store a reference to this function but it will not evaluate it:

var z = (function(x, y) {
    if ((y * (x / 100)) < 1) {
        return (x + Math.ceil(y * (x / 100))); }
    else if ((y * (x / 100)) > 1) {
        return (x + Math.round(y * (x / 100))); }
    else {
        return 0; 
    } 
})(x, y);

Note that (x, y) used inside the anonymous function are not the same as the one passed as arguments at the end which correspond to the two variables declared in the beginning of the foo function.



来源:https://stackoverflow.com/questions/2301851/javascript-when-assigning-an-anonymous-function-to-a-variable-function-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!