JavaScript实例函数与原型函数

mcj*_*erz 29 javascript syntax prototype-programming

可能重复:
在Javascript中使用'prototype'与'this'?

我对各种JavaScript函数的理解如下:

function MyObj() {
    this.propOne = true;
    this.publicInstanceFunc = function() {
        if (propOne)
            return 'public instance function';
    }
    function privateFunc() {
        return 'private function only visible inside this constructor';
    }
}

MyObj.prototype.protoFunc = function() {
    if (this.propOne)
        return 'prototype function shared amongst all instances of MyObj';
}
Run Code Online (Sandbox Code Playgroud)
  1. 这些是正确的吗?
  2. 在什么情况下应该将函数放在原型(例如protoFunc)和构造函数(例如publicInstanceFunc)中?
  3. 使用this正确的方法访问原型函数内的属性?

Chr*_*oph 51

实际上,您可以通过将整个事物包装在自执行函数中来添加另一级别的权限:

var MyObj = (function() { // scoping
    var privateSharedVar = 'foo';

    function privateSharedFunction() {
        // has access to privateSharedVar
        // may also access publicSharedVar via explicit MyObj.prototype
        // can't be called via this
    }

    function MyObj() { // constructor
        var privateInstanceVar = 'bar';
        this.publicInstanceVar = 'baz';

        function privateInstanceFunction() {
            // has access to all vars
            // can't be called via this
        };

        this.publicInstanceMethod = function() {
            // has access to all vars
            // also known as a privileged method
        };
    }

    MyObj.prototype.publicSharedVar = 'quux';

    MyObj.prototype.publicSharedMethod = function() {
        // has access to shared and public vars
        // canonical way for method creation:
        // try to use this as much as possible
    };

    return MyObj;
})();
Run Code Online (Sandbox Code Playgroud)

只有"公共"物业可以从外面通过this.

出于性能原因,您应该避免使用我称之为"实例"的方法:对于每个方法,必须为每个MyObject实例创建一个新的函数对象,而每个"共享"方法只有一个函数对象.