1

I have created a Javascript namespace like so:

var MyApp = function() {
      return {
        someFunction : function(x) {}
             alert(MyApp.y);
      }
}();

This allows me to do this:

MyApp.someFunction(x);

I would like to be able to do the following:

MyApp.y = "test" so that my someFunction can access this variable Y.

Any ideas on how to solve this? I'd like to keep my NS syntax intact so a solution that works with my example code would be nice.

4

2 回答 2

2

你所描述的应该工作。(除非您有语法错误和未使用的参数x。)

var MyApp = function() {
  return {
    someFunction : function(x) {
         alert(MyApp.y);
    }
  }
}();
MyApp.y = 'test';
MyApp.someFunction() // alerts 'test'

另一种方法是将您的外部函数更像构造函数并将 y 作为闭包传递:

var MyApp = (function (y) {
    return {
        y: y,
        someFunction: function () {
            alert(MyApp.y); // or alert(this.y)
        }
    }
} ('test'));
MyApp.someFunction(); // alerts 'test'
于 2011-12-15T13:45:27.630 回答
2

我会用这样的东西:

var MyApp = function() {
    var _y = "default value";
    return {
        someFunction: function(x) {
            console.log(_y);
        },
        setY: function (y) {
            _y = y;
        }
    }
}();

这意味着MyApp.someFunction()在给 赋值之前调用是安全的y。这也意味着变量的内容保持在命名空间的范围内,例如

console.log(MyApp._y); // undefined

以下是如何使用它:

MyApp.someFunction(); // "default value"
MyApp.setY("new value");
MyApp.someFunction(); // "new value"
于 2011-12-15T13:53:41.393 回答