如何在私有方法中以javascript模块化模式访问它?

时间:2013-04-15 12:22:56

标签: javascript

如何在使用javascript模块模式的私有方法时访问此对象(对象)?

我不明白这是如何运作的,我还在努力学习它。

var o = o || {};
o.Assets = (function() {
    "use strict";

    function privateFunc() {
        // how do I get this.assetQ?
    }

    function Assets(assetQ) {
        this.init(assetQ);
    };
    Assets.prototype.assetQ = [];
    Assets.prototype.cache = [];
    Assets.prototype.callback = false;
    /*
Initialize the assets
*/
    Assets.prototype.init = function(assetQ) {
        if (assetQ) {
            this.assetQ = assetQ;
        }
    };
    return Assets;
})();

1 个答案:

答案 0 :(得分:1)

当您使用privateFunc方法拨打Assets时,请使用privateFunc.call( this ),然后在this.assetQ内使用privateFunc

function privateFunc() {
    console.log(this.assetQ);
}

...

Assets.prototype.init = function(assetQ) {
    if (assetQ) {
        this.assetQ = assetQ;
    }
    privateFunc.call( this );
};

如果您的私有函数接受参数,您可以在上下文参数之后通常在.call中传递它们:

privateFunc.call( this, 1, 2, 3 );

function privateFunc( a, b, c ) {
  //a is 1, b is 2 etc..
}