JavaScript 对象字面量方法:递归调用
是否可以从对象字面量递归调用方法?
例如:
(function () {
'use strict';
var abc = ['A', 'B', 'C'],
obj = {
f: function () {
if (abc.length) {
abc.shift();
f(); // Recursive call
}
}
};
obj.f();
}());
错误:'f' 在定义之前就被使用了。
谢谢。
Is it possible to call recursively a method from an object literal?
For example:
(function () {
'use strict';
var abc = ['A', 'B', 'C'],
obj = {
f: function () {
if (abc.length) {
abc.shift();
f(); // Recursive call
}
}
};
obj.f();
}());
Error: 'f' was used before it was defined.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过使用命名函数表达式:
必读:http:// kangax.github.com/nfe/
You can, by using a named function expression:
A must-read: http://kangax.github.com/nfe/
f
是对象上的一个方法。因此,当您处于f
中时,this
将成为f
所附加的对象。因此,要递归调用f
,请使用this.f()
请注意,在
f
内部,this
只会如果f
作为方法调用,则为当前对象:obj.f();
如果执行类似以下操作:
obj.f.call(lala);
,那么this
现在将是拉拉。如果您执行以下操作:现在
this
是f
内部的全局对象(或在严格模式下未定义)f
is a method on your object. As a result, when you're inf
,this
will be the object to whichf
is attached. So to recursively callf
, usethis.f()
Just note that inside of
f
,this
will only be the current object iff
is invoked as a method:obj.f();
If you do somethinig like:
obj.f.call(lala);
, thenthis
will now belala
. And if you do something like:Now
this
is the global object inside off
(or undefined in strict mode)代码中的任何位置都没有定义名为
f
的变量。使用obj.f()
(如果您知道this
指向它应该指向的位置,则使用this.f
)。There's no variable called
f
defined anywhere in your code. Useobj.f()
(orthis.f
if you knowthis
points to where it should).