views:

38

answers:

3

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 do I make the method in a way that I can run it both inside the object and from the outside

Thanks

+1  A: 

When you define the function use the name just once, like this:

obj = function(){
  this.getMail = function(){
    alert("bob");
  }
}

Now you can use this.getMail() in there, you can see a working example here.

Nick Craver
Thanks for the link, really useful tool.
John
+1  A: 

Building a robust definition for your object is recommended. Build a prototype for it, then if you ever need two or more, you can make instances of them. I show below how to build a prototype, add methods that call eachother, and how to instantiate the object.

obj = function () {} //define the 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)
Alex Mcp
Thanks, not familiar with prototype. I will check it out
John
A: 

here you go:

var obj = function() {

    function getMail() {
        alert('hai!');
    }

    this.getMail = getMail;
    //Here I would like to run the get mail once but this.getMail() or getMail() wont work

    getMail();
}

var mail = new obj();
mail.getMail();
lincolnk