在另一个函数中访问变量,返回undefined - JavaScript

时间:2013-10-18 09:50:21

标签: javascript function closures scope scoping

我正在尝试访问另一个函数中存在的变量,但是我无法,它为我提供了未定义的函数(getMess()如下所示)我正在这样做。 根据下面的代码,我希望通过myfunction1访问“value1”,如下所示。 代码:

var namespace ={
    myfunction1: function(){
        namespace.myfunction2.getMess();   // I need to access value1 here in this function
    },

    myfunction2: function(message1,message2){
        var value1 = message1;
        var value2 = message2;
        return{
          getMess: function(){ return value1;}
          getLab: function() { return value2;}
        }
    }
}

namespace.myfunction2("hello","bye"); // this basically just sets the 2 values on page load

我刚发布了原始问题的另一个问题:Read resource file entry in javascript - MVC application

2 个答案:

答案 0 :(得分:3)

你可以这样做:

myfunction2: function(message1,message2){

    var value1 = message1;
    var value2 = message2;

    namespace.myfunction2.getMess: function(){ return value1;}
    namespace.myfunction2.getLab: function() { return value2;}
}

但这非常糟糕(为函数对象分配属性)。最好使用模块模式将整个事物重构为emulate private and privileged members

e.g。

var namespace = (function() {

    // Private members
    var value1, value2;

    return {

      // Privileged methd to read private member values
      fn1: function() {
        return namespace.fn2.getMess1();
      },

      // Privileged methods to set and get private member values
      fn2: {
        setMess: function(message1, message2) {
          value1 = message1;
          value2 = message2;
        },

        getMess1: function() {
          return value1;
        },

        getMess2: function() {
          return value2;
        }
      }
    }
}());

namespace.fn2.setMess("hello","bye");

alert(namespace.fn1()); // hello

答案 1 :(得分:0)

这对我来说似乎很奇怪,但首先你要重新调整一个物体并在你试图返回的两个函数之间错过,

var namespace ={
    myfunction1: function(){
        var jamie = namespace.myfunction2("hello","bye");   // save returned value so we can use them later.
        console.info(jamie.getMess); //as we already executed the value just refer to them
    },

    myfunction2: function(message1,message2){
        var value1 = message1;
        var value2 = message2;
        return{
          getMess: function(){ return value1;}(), //return self executing functions to return values without the need to run them again.
          getLab: function(){ return value2;}()
        }
    }
}
namespace.myfunction1();

虽然我仍然不确定你想要实现什么,但这是我如何在两个函数之间传递值,而不是将变量声明为namespace,而只是以这种方式全局赋值。