简体   繁体   中英

Access public function from private function in JavaScript

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.?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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