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

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

问题描述


可能重复:

在Javascript中使用'原型'与'这个'?

我对不同类型的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. 使用这个访问原型函数中的属性的正确方法是什么?

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

只有'公共'物业可以从外面通过来访问

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

出于性能原因,你应该避免我称之为实例的方法:对于每一种方法,必须为每个方法创建一个新的函数对象 MyObject 实例,而每个'shared'方法只有一个函数对象。

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天全站免登陆