【问题标题】:Calling javascript method from from inside object从对象内部调用 javascript 方法
【发布时间】:2010-05-12 01:56:50
【问题描述】:
我正在为 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
methods
naming
【解决方案2】:
给你:
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();
【解决方案3】:
建议为您的对象建立一个健壮的定义。为它构建一个原型,然后如果您需要两个或更多,您可以制作它们的实例。我将在下面展示如何构建原型、添加相互调用的方法以及如何实例化对象。
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)