从对象内部调用javascript方法

从对象内部调用javascript方法,javascript,methods,naming,Javascript,Methods,Naming,我正在努力使用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(); 如何使方法既可以在对象内部运行,也可以从外部运行 谢谢定

我正在努力使用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();
如何使方法既可以在对象内部运行,也可以从外部运行


谢谢

定义函数时只需使用一次名称,如下所示:

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

现在,您可以在其中使用
this.getMail()

建议为对象构建一个健壮的定义。为它构建一个原型,然后如果您需要两个或更多,您可以创建它们的实例。我将在下面展示如何构建原型、添加相互调用的方法以及如何实例化对象

obj=function(){}//定义空对象

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)
给你:

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

谢谢,不熟悉原型。我会查出来的谢谢你的链接,非常有用的工具。