Javascript - 从函数返回值

Javascript - return value from function

本文关键字:返回值 函数 Javascript      更新时间:2023-09-26

我有一个像这样初始化的JS库:

$("#container").mylibrary({
    progressBarWidth: "480px",
    fileUploadProgress: function(progress) {
        // handle upload progress here
    },
    // etc. other callbacks and variables continue
)};

我想更改此设置,以便我可以查看用户是否在移动设备上,如果是,则为进度条宽度返回不同的值。如何在此处内联一个小函数并返回一个值?我试过这个,没有运气:

    progressBarWidth: (function() {
         // do some math here
         r = '480px';   
         return r;
    }),

您定义了函数,但没有执行它。 您可以通过在匿名函数后添加括号来自行执行匿名函数:

progressBarWidth: (function() {
     // do some math here
     r = '480px';   
     return r;
})()

像这样吗?(丑...但我不明白你的问题;-)

function myFunction() {
 var r = '480px';
 return r;
};
$("#container").mylibrary({
    progressBarWidth: myFunction(),
    fileUploadProgress: function(progress) {
        // handle upload progress here
    },
    // etc. other callbacks and variables continue
)};