在函数外访问 JavaScript 函数变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18049118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:35:04  来源:igfitidea点击:

Accessing JavaScript function variables outside of the function

javascriptparameters

提问by mwilson

I apoligize for my newbness but I'm not clearly understanding how to access variables within a function outside of the function. I understand that you need to pass them some how but I'm not 100% sure on the whys and hows.

我为我的新手道歉,但我不清楚如何在函数外访问函数内的变量。我知道您需要向他们传递一些方法,但我不能 100% 确定原因和方法。

Taking the below code for example, I want to use the var degreethroughout the code outside of the function. How do I do it?

以下面的代码为例,我想var degree在函数之外的整个代码中使用。我该怎么做?

function DegreeToMil() 
{

//Degree's to Mils: 1 Degree = 17.777778 Mils

var degree = 10;
var mils = degree * 17.777778;

return mils;

 }

回答by Pandacoder

It is actually fairly simple, just define it outside of the function.

其实很简单,在函数外定义就行了。

Edit: Updated with an example, and comments explaining what was done and how it works.

编辑:更新了一个例子,并解释了做了什么以及它是如何工作的评论。

    DegreesToMils.degrees = 10; /* This is a static variable declaration to make sure it isn't undefined
                             * See note 1 below */

function DegreesToMils(degrees) {
    if (degrees !== undefined) {
        DegreesToMils.degrees = degrees; /* If the parameter is defined, 
                                          * it will update the static variable */
    }

    var milsPerDegree = 17.777778; /* This is a variable created and accessible within the function */

    return DegreesToMils.degrees * milsPerDegree; /* The function will return 177.77778 */
}

console.log(DegreesToMils.degrees); /* Prints 10, Note 1: This would be undefined if
                                     * not declared before the first call to DegreesToMils() with a 
                                     * defined parameter
                                     */
console.log(DegreesToMils(10)); /* Prints 177.77778 */
console.log(DegreesToMils(9)); /* Prints 160.00000200000002, Sets DegreesToMils.degrees to 9 */
console.log(DegreesToMils.degrees); /* Prints 9 */

回答by mwilson

function DegreeToMil() 
{

    //Degree's to Mils: 1 Degree = 17.777778 Mils

    var degree = 10;
    var mils = degree * 17.777778;
    var result = [degree, mils]; // it's an array
    return result;
}

// use it like this

var myResult = DegreeToMil();
console.log(myResult[0]); // degree
console.log(myResult[1]); // mils