Calling a javascript method from within an object
I am struggling with methods in JavaScript.
obj = function(){
this.getMail = function getMail (){
}
//Here I would like to run the get mail once but this.getMail() or getMail() wont work
}
var mail = new obj();
mail.getMail();
How to make a method such that I can run it both inside the object and outside
thanks
+2
a source to share
3 answers
When you define a function, use the name only once, for example:
obj = function(){
this.getMail = function(){
alert("bob");
}
}
Now you can use this.getMail()
there, you can see a working example here .
+4
a source to share
It is recommended that you create a robust definition for your object. Create a prototype for it, then if you ever need two or more, you can make instances of them. Below, I'll cover how to create a prototype, add methods that call each other, and how to instantiate an object.
obj = function () {} // define an empty object
obj.prototype.getMail = function () {
//this is a function on new instances of that object
//whatever code you like
return mail;
}
obj.prototype.otherMethod = function () {
//this is another function that can access obj.getMail via 'this'
this.getMail();
}
var test = new obj; //make a new instance
test.getMail(); //call the first method
test.otherMethod(); //call the second method (that has access to the first)
0
a source to share