0

我正在尝试访问另一个函数中存在的变量,但我无法访问,它给了我未定义的函数,通过该函数(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

4

2 回答 2

3

You could do:

myfunction2: function(message1,message2){

    var value1 = message1;
    var value2 = message2;

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

but that's pretty awful (assigning properties to a function object). Better to refactor the whole thing using the module pattern to 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
于 2013-10-18T09:57:35.773 回答
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();

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

于 2013-10-18T10:00:57.680 回答