Javascript calling function within the parent function

Calling public function in private and public functions.

var greeting = function()
{

	this.publicHello = function(){ console.log("Hello"); }

	this.publicHello(); // calling the publicHello when this object is created

	this.publicSayHello = function()
	{
		this.publicHello(); // calling the public function in public function
	}
        var _this = this;
	function privateSayHello()
	{
		_this.publicHello(); // calling the public function in a private function
	}
}

var g = new greeting(); // prints Hello
g.publicHello();        // prints Hello
g.publicSayHello();	// prints Hello 
g.privateSayHello();	// Uncaught TypeError: Object [object Object] has no method 'privateSayHello'

Calling private function in private and public functions.

var greeting2 = function()
{

	var privateHello = function(){ console.log("Hello"); }

	privateHello.call(this); // calling the privateHello when this object is created

	this.publicSayHello = function()
	{
		privateHello.call(this); // calling the private function in public function
	}
	function privateSayHello()
	{
		privateHello.call(this); // calling the private function in a private function
	}
	privateSayHello.call(this); // calling the privateSayHello when this object is created
}
var g = new greeting2(); // prints Hello Hello
g.publicSayHello();	 // prints Hello 

Summary:

  • To call a public function, it needs to have the keyword this.
  • Public function can be called on the object after it is created.
  • To call a private function, it needs to be called by functionname.call(this);
  • Private function cannot be called on the object after is is created, it can only be called with the function it was defined.
  • Search within Codexpedia

    Custom Search

    Search the entire web

    Custom Search