I´ve defined a class like this:
function Class1(){
this.Func1 = function(){
/* Methods and vars */
};
function Func2(){
/* Methods and vars */
};
};
I want to find out a way to call the public method (or get the value of a public variable) from the private one (Func2()). Any sugestions?
Pd: Sorry if the terminology I used is strongly oriented to objects, because I am a C++ programer, and I'm kinda newby in javascript programming.
I´ve defined a class like this:
function Class1(){
this.Func1 = function(){
/* Methods and vars */
};
function Func2(){
/* Methods and vars */
};
};
I want to find out a way to call the public method (or get the value of a public variable) from the private one (Func2()). Any sugestions?
Pd: Sorry if the terminology I used is strongly oriented to objects, because I am a C++ programer, and I'm kinda newby in javascript programming.
Share Improve this question edited Jun 21, 2011 at 18:41 Sophie Alpert 143k36 gold badges225 silver badges243 bronze badges asked Jun 21, 2011 at 5:40 Jesufer VnJesufer Vn 13.8k6 gold badges21 silver badges28 bronze badges 4-
Func2
is actually the "private method" here, andFunc1
"public". – Casey Chu Commented Jun 21, 2011 at 5:42 - Sorry, I was so fast at wirting the question – Jesufer Vn Commented Jun 21, 2011 at 5:44
- You should write 'this.Func1 = new function()' instead of 'this.Func1() = new function()' – recamshak Commented Jun 21, 2011 at 5:47
- 1 A little nitpicking here: you should write most functions and methods with camelCase (first letter lowercase) Write your constructor-functions with CamelCase (first letter uppercase). Source: javascript.crockford./code.html – Niels Bom Commented Dec 16, 2011 at 10:00
3 Answers
Reset to default 8From Func1
, you can call Func2
directly:
this.Func1 = function() {
Func2();
};
However, you cannot do the same to call Func1
from Func2
because Func2
will (probably) have a different scope and different definition of this
when it is called; this.Func1
will be undefined. As alx suggested below, you can save the scope using another variable that will retain its value when used from the inside function. You can also save a reference to Func1
in local scope as follows:
var Func1 = this.Func1 = function() {
// fun stuff
};
function Func2() {
Func1();
}
This works because it does not rely on the changing reference this
.
use closure:
function Class1(){
this.Func1 = function(){
/* Methods and vars */
};
var me = this;
function Func2(){
me.Func1();
};
};
being declared in the same scope, the public method is aware of the private one, thus you can just simply call it :
function Object1(){
this.publicMethod = function(){
alert("I'm a public method ;)");
};
var that = this;
function privateMethod(){
return that.publicMethod.apply(that,arguments);
};
};