Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling one prototype method inside another in javascript

var Ob = function(){   }  Ob.prototype.add = function(){     inc()  }  Ob.prototype.inc = function(){     alert(' Inc called ');  }  window.onload = function(){ var o = new Ob(); o.add(); } 

I would like to call something like this,how can i call, ofcourse i put inc as inner function to add I can do that but without having the inner function. how do i do that ?

like image 248
indianwebdevil Avatar asked Jan 08 '12 15:01

indianwebdevil


People also ask

How do you call one method from another in JavaScript?

The JavaScript call() Method It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

What is prototype in JavaScript stack overflow?

1. 13. -1: prototype is a property of constructor functions, not instances, ie your code is wrong!


1 Answers

It's easy:

Ob.prototype.add = function(){     this.inc() }  Ob.prototype.inc = function(){     alert(' Inc called '); } 

When you create the instance of Ob properties from prototype are copied to the object. If you want to access the methods of instance from within its another method you could use this.

like image 127
bjornd Avatar answered Oct 09 '22 08:10

bjornd