问题
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