简体   繁体   English

从JavaScript中的私有函数访问公共函数

[英]Access public function from private function in JavaScript

I have recently started with OOP in JavaScript. 我最近开始使用JavaScript进行OOP And, I am allover confused with these things. 而且,我对这些事情感到困惑。 I know JavaScript is entirely different from Java. 我知道JavaScript与Java完全不同。 But this is causing problem. 但这引起了问题。

What I am trying to implement: 我正在尝试实现的是:

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

This is throwing an error, which says: 这引发了一个错误,说:

Uncaught TypeError: undefined is not a function 未捕获的TypeError:undefined不是函数

For 对于

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

What should I do? 我该怎么办? How to implement this part.? 如何实现这部分? have I misunderstood something about JavaScript classes.? 我是否误解了JavaScript类。

Look at this answer. 这个答案。

You wrap the public functions in an object literal and return it. 您将公共函数包装在对象文字中并返回它。 You can thus call the private functions in the object literal functions. 因此,您可以在对象文字函数中调用私有函数。

You should read about hoisting and differences between declaring function and function expression. 您应该阅读有关提升和声明函数与函数表达式之间的区别的信息。

Your code does not work because js knows that there is declared var publicFunctionSet (function expression) but it is not a function when privateFunction(x) is being declared. 您的代码不起作用,因为js知道已声明var publicFunctionSet(函数表达式),但在声明privateFunction(x)时它不是函数。

PS. PS。 @Akash Pradhan answer will solve your problem, but I guess you still should check the background and undestand why it is not working the way you tried :) @Akash Pradhan的答案可以解决您的问题,但是我想您仍然应该检查背景并理解为什么它无法按您尝试的方式工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM