在JavaScript中从私有函数访问公共函数 [英] Access public function from private function in JavaScript

查看:104
本文介绍了在JavaScript中从私有函数访问公共函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在JavaScript中使用 OOP 开始。而且,我对这些事情感到困惑。我知道JavaScript与Java完全不同。但这会导致问题。

I have recently started with OOP in JavaScript. And, I am allover confused with these things. I know JavaScript is entirely different from Java. But this is causing problem.

我想要实现的目标:

function myClass() {
    //Declare private variable
    var privateVar = '';

    //To act as constructor
    privateFunction('Hello');

    //Getter
    this.publicFunctionGet = function() {
        return privateVar;
    }
    //Setter
    this.publicFunctionSet = function(x) {
        privateVar = x;
    }
    function privateFunction(x) {
        this.publicFunctionSet(x);
    }
}

//Create object of myClass
var me = new myClass();
alert(me.publicFunctionGet());

这是一个错误,它说:


Uncaught TypeError:undefined不是函数

Uncaught TypeError: undefined is not a function

对于

function privateFunction(x) {
    this.publicFunctionSet(x);
}

我该怎么办?如何实现这一部分。我误解了一些关于JavaScript类的东西吗?

What should I do? How to implement this part.? have I misunderstood something about JavaScript classes.?

推荐答案

看看这个答案。

你包装公众在对象文字中起作用并返回它。因此,您可以在对象文字函数中调用私有函数。

You wrap the public functions in an object literal and return it. You can thus call the private functions in the object literal functions.

这篇关于在JavaScript中从私有函数访问公共函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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