0

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

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

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;
})();
4

1 回答 1

1

当您privateFunc从 的方法调用时Assets,使用privateFunc.call( this )then use this.assetQinside 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..
}
于 2013-04-15T12:25:42.583 回答