1

我正在使用看起来像这样的模式(伪示例):

var FOO = (function(foo) {

    var foo = foo || {},
    setThis = 'someValue';

    //--------------------------------------------------------------------------
    //
    // Public methods:
    //
    //--------------------------------------------------------------------------

    foo.init = function(bar) {

        this.blah = [];

        // Constructor stuff here...

    };

    foo.doSomething = function(bar) {

        if (bar) {

            this.doSomethingElse();

            // Stuff here...

        }

    };

    foo.doSomethingElse = function() {

        // Stuff here...

    };

    //--------------------------------------------------------------------------
    //
    // Private methods:
    //
    //--------------------------------------------------------------------------

    foo._imPrivate = function() {

        // ... stuff here ...

        this.blah = xyz; // References this.

    };

    foo._morePrivate = function(el) {

        // No reference to this.

    };

    foo._otherPrivate = function(el) {

        // No reference to this.

    };

    return foo; // Expose the methods.

}(FOO || {}));

像这样实例化:

window.onload = function() { FOO.init(stuff); }

三个问题:

  1. 如果我的“私有”方法不引用this,我是否应该将它们设为“标准”函数(function _imPrivate() { ... }例如)?我问的原因:我有一些引用的方法this,但我不想让它们公开访问;我还有一些不引用的“实用程序”方法this......引用的方法可以this是标准函数(在模块模式的上下文中)吗?
  2. 有人可以提供一个示例来说明我将如何为setThis变量实现设置器吗?
  3. Do you see any room for improvements in the above code?
4

2 回答 2

3

The "private" methods aren't private at all, they're public. The OP doesn't seem to take any advantage of closures available from the use of an immediately invoked function expression (IIFE).

The value of a function's this is set by how you call a function, it isn't static (unless you use ES5 bind). It has nothing to do with "context" (at least not in the way context is used in ECMA-262, which is how the word should be used in the context of javascript).

Douglas Crockford's Private Members in JavaScript will help.

If you post a real example of what you are trying to do, you will likely get more help on how to exploit the module pattern in its implementation.

于 2012-07-23T22:50:46.627 回答
2

1.

You can do _imPrivate.call(this, arg1, arg2,...);

And in this case this in the _imPrivate function will refer to the particular instance.

2.

var setThis = 'someValue';

foo.setter = function(value) {
    setThis = value;
};
于 2012-07-23T22:27:09.457 回答