2010-05-12 165 views
2

我很努力地使用JavaScript中的方法。从对象内部调用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(); 

如何让我的方式方法,我既可以在物体内部和外部

由于运行

回答

4

当你定义功能使用的名称只有一次,就像这样的:

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

现在你可以在那里使用this.getMail()you can see a working example here

+0

感谢您的链接,真正有用的工具。 – John 2010-05-12 02:16:59

0

建议为您的对象构建强大的定义。为它建立一个原型,如果你需要两个或更多,你可以创建它们的实例。我在下面展示如何构建原型,添加调用eachother的方法以及如何实例化对象。

OBJ =函数(){} //定义空对象

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

谢谢,不熟悉原型。我会看看 – John 2010-05-12 02:15:09

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