从内部对象调用javascript方法

时间:2010-05-12 01:56:50

标签: 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();

如何以可在对象内部和外部

运行方式的方式创建方法

由于

3 个答案:

答案 0 :(得分:4)

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

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

现在,您可以在you can see a working example here使用this.getMail()

答案 1 :(得分:0)

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

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)

答案 2 :(得分:0)

你去:

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