【问题标题】:How to access variables declared in a function, from another function using javascript如何使用javascript从另一个函数访问函数中声明的变量
【发布时间】:2015-06-29 14:06:15
【问题描述】:

在 Javascript 中,我需要从另一个函数访问函数中声明的变量,例如:

function abc()
{
  var a = 'StackOverflow';
}

function abc之外我需要访问variable a

我试过了:

var s = function abc()
{
    var a = 'StackOverflow';
} 

alert(s.a);

我可以通过将a 的值声明为全局变量来访问它,但我想知道如何从function abc 的引用中访问它

请解决这个问题

谢谢。

【问题讨论】:

标签: javascript jquery function


【解决方案1】:

试试这个:

function abc()
{
    this.a = 'StackOverflow';
    this.b = 'jQuery Core';
    this.c = 'JavaScript';
} 

var s = new abc();

alert( s.a );

或者,如果您没有其他操作,请使用此表示法:

var s = {
   a: 'StackOverflow',
   b: 'jQuery Core',
   c: 'JavaScript'
}; 

alert( s.a );

【讨论】:

  • 如果我在function abc 中声明了一个variable 并在inner function 中为其分配了一个值...
  • 函数中定义的变量对于该函数是局部的,除非变量被定义为上述函数的属性。
  • 这些并不是你的abc 函数中的真正变量。您应该解释 OP 的要求是如何不可能的,以及如何实现类似的目标。还要说明如果在没有new 的情况下调用abc(),您正在创建全局变量
【解决方案2】:

这就是 JavaScript 对象!使用这种方式:

var s = new function abc()
{
    this.a = 'StackOverflow';
}

然后这样调用:

s.a; , e.g alert(s.a);

或以其他方式:

var s = function abc()
{
    var a = 'StackOverflow';
    return {
        a: a
    };
}

你可以得到它:

s().a;

【讨论】:

  • s.a();? a 不是 function
【解决方案3】:

您可以使用具有自己属性的函数:

var s = function () {
    function abc(r) {           // declare function with one parameter as example
        return Math.PI * r * r; // do something, here return area of circle as example
    }
    abc.a = 'StackOverflow';    // set property a with value
    return abc;                 // return function with property
}();                            // IIFE
document.getElementById('out').innerHTML = s.a + '<br>' + s(3);
&lt;div id="out"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多