访问函数外部的对象变量

我正在尝试从js函数中获取作为对象返回的变量值。 我究竟做错了什么?

function myFunction() {
  vara = 1;
  varb = 2;
  var myobj = {'vara': vara, 'varb': varb};
  return myobj;
}
myFunction();
var getA = myobj.vara; // Console is saying can't find variable myobj
评论
  • 逢水之
    逢水之 回复

    You'll have to assign the returned object from the myFunction() to a variable, then you can access it, something like the following:

    function myFunction() {
      vara = 1;
      varb = 2;
      var myobj = { vara: vara, varb: varb };
      return myobj;
    }
    
    var obj = myFunction(); // Assign the return of the function to a variable
    var getA = obj.vara; // Then you can access it
    
    console.log(getA)
  • bquia
    bquia 回复

    在函数内部创建变量时,它在函数内部具有局部作用域。不能在外部访问。返回后,您必须分配一些变量以访问这些属性。

    function myFunction() {
      vara = 1;
      varb = 2;
      // Local functaional scope
      var myobj = { vara: vara, varb: varb };
      return myobj; // return here
    }
    const obj = myFunction(); // capture return in obj variable
    
    var getA = obj.vara; // access the value
    
    console.log(getA)