JavaScript 实例函数与原型函数 [英] JavaScript instance functions versus prototype functions

查看:25
本文介绍了JavaScript 实例函数与原型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在Javascript中使用'prototype'还是'this'?

我对不同种类的 JavaScript 函数的理解如下:

My understanding of the different kinds of JavaScript functions are as follows:

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';
}

  1. 这些正确吗?
  2. 在什么情况下,应该将函数放在原型上(例如 protoFunc)还是在构造函数中(例如 publicInstanceFunc)?
  3. 使用this是访问原型函数内属性的正确方法吗?
  1. Are these correct?
  2. In what cases should one put functions on the prototype (e.g. protoFunc) vs. in the constructor (e.g. publicInstanceFunc)?
  3. Is using this the correct way to access properties inside prototype functions?

推荐答案

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

You can actually add another level of privilege via wrapping the whole thing in a self-executing function:

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

只有公共"属性可以通过this从外部访问.

Only 'public' properties can be accessed from outside via this.

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

For performance reasons, you should avoid what I called 'instance' methods: For each of these, a new function object must be created for each MyObject instance, whereas there's only a single function object per 'shared' method.

这篇关于JavaScript 实例函数与原型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆