1

我想重写一个文件以合并公共和私有变量。我正在尝试做这样的事情:

var PrivateFunc = (function() {

  //Private Functions
  var _iAmPrivate = function(param, args){
    //code
  }

  var _soAmI = function(param){
    //code
  }

  return PrivateFunc;
})();

var PubObj = {
  someVar: 1,
  getPrivFunc: PrivateFunc,

  publicFunc: function(param){
    //This doesnt work
    this.getPrivFunc._iAmPrivate(someVar, param);
    //This doesn't either
    getPrivFunc._soAmI(param);
  }

};

我是一个“getPrivFunc未定义”的错误。我认为搬到getPrivFunc外面PubObj可以工作,但我遇到了同样的问题。调用PrivateFunc也给出错误。我觉得这是一个愚蠢的错误,我只是没有看到它。

也许有更好的方法来做到这一点?

4

2 回答 2

1

Anything declared with a var is going to be inaccessible outside the function it's declared in. You could do something like the following, instead. The important thing to keep in mind is that where your vars occur defines the scope of their declaration.

var PubObj;
(function() {
  PubObj = {
    someVar: 1,

    publicFunc: function(param) {
      _iAmPrivate(this.someVar, param);
      _soAmI(param);
    }
  };

  //Inner Functions
  var _iAmPrivate = function(param, args) {
    //code
  };

  var _soAmI = function(param) {
    //code
  };
})();
于 2013-06-21T19:14:18.450 回答
1

您的 PrivateFunc 没有返回任何内容,因为您使用的是 OOP 概念而没有正确实施。如果我们创建一个为您的每个私有函数设置属性this的函数,您可以使用new关键字创建它的实例。

var PrivateFunc = new function() {
  this._iAmPrivate = function(param, args) {
    console.log('PrivateFunc._iAmPrivate called with', param, args);
  }

  this._soAmI = function(param) {
    console.log('PrivateFunc._soAmI called with', param);
  }
}();

然后我们可以从您的 PubObj 内部访问 PrivateFunc。

var PubObj = {
  someVar: 1,
  getPrivFunc: PrivateFunc,

  publicFunc: function(param) {
    this.getPrivFunc._iAmPrivate(this.someVar, param);
    this.getPrivFunc._soAmI(param);
  }
};

当我们调用 PubObj.publicFunc('test') 时,我们得到:

PubObj.publicFunc('test')
> PrivateFunc._iAmPrivate called with 1 test
> PrivateFunc._soAmI called with test
于 2013-06-21T19:30:07.893 回答