访问“公开"网站来自“私人"的方法javascript类中的方法 [英] Accessing "Public" methods from "Private" methods in javascript class

查看:62
本文介绍了访问“公开"网站来自“私人"的方法javascript类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从类中的私有"函数中调用公共" javascript函数?

Is there a way to call "public" javascript functions from "private" ones within a class?

查看以下课程:

function Class()
{
    this.publicMethod = function()
    {
        alert("hello");
    }

    privateMethod = function()
    {
        publicMethod();
    }

    this.test = function()
    {
        privateMethod();
    }
}

这是我运行的代码:

var class = new Class();
class.test();

Firebug给出此错误:

Firebug gives this error:

publicMethod未定义:[对此错误打破] publicMethod();

还有其他方法可以在privateMethod()中调用publicMethod()而不访问全局类变量[即class.publicMethod()]?

Is there some other way to call publicMethod() within privateMethod() without accessing the global class variable [i.e. class.publicMethod()]?

推荐答案

被接受的答案可能会带来不良后果,即在每个实例中将分别创建publicMethodtestprivateMethod的副本.避免这种情况的成语是:

The accepted answer has the possibly undesirable side effect that separate copies of publicMethod, test, and privateMethod will be created in each instance. The idiom for avoiding this is:

function Class()
{}

Class.prototype=(function()
{
    var privateMethod = function(self)
    {
        self.publicMethod();
    }


    return 
    {
        publicMethod: function()
        {
            alert("hello");
        },
        test: function()
        {
            privateMethod(this);
        }
    };
}());

换句话说,您需要将this作为参数传递给私有函数.作为回报,您将获得一个 true 原型,而不必使用其自己的私有和公共功能版本来污染每个实例.

In other words, you need to pass the this to the private function as an argument. In return, you get a true prototype without having to pollute each instance with its own versions of the private and public functions.

这篇关于访问“公开"网站来自“私人"的方法javascript类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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