Access public function from private function in JavaScript

回眸只為那壹抹淺笑 提交于 2019-12-08 06:41:03

问题


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.

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

For

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

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


回答1:


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.




回答2:


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.

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 :)



来源:https://stackoverflow.com/questions/28294768/access-public-function-from-private-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!