Calling javascript method from from inside object - Stack Overflow

I am struggling with methods in JavaScript. obj = function(){this.getMail = function getMail (){}Her

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

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

Share asked May 12, 2010 at 1:56 JohnJohn 4044 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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.

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();

Building a robust definition for your object is remended. 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)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745067836a4609362.html

相关推荐

  • Calling javascript method from from inside object - Stack Overflow

    I am struggling with methods in JavaScript. obj = function(){this.getMail = function getMail (){}Her

    16小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信