Mootools 类 - 在函数内调用函数
我现在正在学习 Mootools 课程,有些东西我似乎无法理解或找到一个合适的例子。
基本上,我需要能够调用同一类的不同函数中的函数;下面的示例:
var Bob = new Class({
initialize: function () {
this.message = 'Hello';
},
someOther: function() {
this.message2 = 'Bob';
},
getMessage: function() {
return this.someOther();
},
});
window.addEvent('domready', function() {
var map = new Bob;
alert(map.getMessage());
});
从这段代码中,我本以为警报会生成已在函数“someOther”中设置的“Bob”,但它输出了一条未定义的消息。
谁能帮忙或指出我哪里出错了?
提前致谢,
I'm learning Mootools classes at the moment and there's something that I can't seem to get my head around or find a decent example.
Basically, I need to be able to call a function within a different function of the same class; example below:
var Bob = new Class({
initialize: function () {
this.message = 'Hello';
},
someOther: function() {
this.message2 = 'Bob';
},
getMessage: function() {
return this.someOther();
},
});
window.addEvent('domready', function() {
var map = new Bob;
alert(map.getMessage());
});
From this code, I would have thought that the alert would produce 'Bob' which has been set in the function 'someOther' but it's outputting a undefined message.
Can anyone help or point out where I'm going wrong?
Thanks in advance,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
呃不完全是。
someOther
本身没有返回值,它是一个 setter。你调用它,它会将this.message2
设置到类中,但它什么也不返回。当 getter 时,方法应该返回 this(实例,因此使其可链接)或一个值。无论如何,你可以让它设置属性并返回它,如下所示:
不过,从语义上讲,你想要有 1 个 getter。
.getMessage
应该只是返回 this.message
- 您可以编写一个不同的方法来调用 someOther 并返回它。看看我前几天写的类上下文中的 getter/setter 模式:
http://fragged.org/using- overridesetter-overloadgetter-to-make-flexible-functions-in-mootools_1451.html
等,如需更多帮助,请查看keetology 博客或 davidwalsh.name - 或 mootorial - 有大量类使用和结构的示例。
这里列出了最关键的:https://stackoverflow.com/tags/mootools/info
er not quite.
someOther
has no return value in itself, it's a setter. you invoke it and it will setthis.message2
into the class but it returns nothing. methods shouldreturn this
(the instance, so making it chainable) or a value, when a getter.anyway, you can make it set the property and return it like so:
though, semantically, you want to have 1 getter.
.getMessage
should justreturn this.message
- you can write a different method that calls someOther and returns it.have a look at this pattern for a getter/setter in a class context I wrote the other day:
http://fragged.org/using-overloadsetter-overloadgetter-to-make-flexible-functions-in-mootools_1451.html
etc etc. for more help, look at the keetology blogs or davidwalsh.name - or the mootorial - plenty of examples of class use and structure.
most key ones are listed here: https://stackoverflow.com/tags/mootools/info