在该对象的函数内迭代该对象的所有成员
如果我能做到这一点,那就非常方便了:
var MyObject = function(param1, param2, ... paramN)
{
this.var1 = stuff;
this.var2 = moreStuff;
.
.
.
this.varN = nStuff;
this.validate = function()
{
for(var current in this)
{
alert(current);
//validate all member variables (even this function I suppose)
}
};
};
然而,这似乎并没有达到我想要的效果。 我意识到循环最终必须循环其父函数(毫不奇怪,这也不会发生)。
这是不可能的,因为第二个函数中的“this”指的是第二个函数而不是第一个函数? 或者关键字“this”只是公共成员的声明运算符,而不是对外部对象的引用?
我认为以这种方式获得我想要的东西是不可能的,但是还有其他方法可以实现这种行为吗?
It would be exceedingly handy if I could do this:
var MyObject = function(param1, param2, ... paramN)
{
this.var1 = stuff;
this.var2 = moreStuff;
.
.
.
this.varN = nStuff;
this.validate = function()
{
for(var current in this)
{
alert(current);
//validate all member variables (even this function I suppose)
}
};
};
This however does not seem to do what I would want. I realize that the loop would eventually have to loop over it's parent function (which also, not surprisingly, does not happen).
Is this impossible because the 'this' in the second function refers to the second function and not the first? Or is the keyword 'this' only a declaration operator for a public member and not a reference to the outer object ?
I figure getting what I want this way is not possible but is there another way I can go about achieving this behaviour ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您如何调用
validate
?以下代码对我来说效果很好:
How are you calling
validate
?The following code works fine for me:
我认为您正在尝试获取成员的值并以错误的方式处理它,因此请尝试以下操作:
解释一下:循环首先检查该属性是否是用户定义的属性,而不是从 Object 对象继承。 它还检查该成员不是一个函数(如 validate()),然后警告该成员的值。
Douglas Crockford(JS 之父)建议将 hasown 属性检查作为迭代成员时的最佳实践。
希望这会有所帮助,
Darko
编辑:忘记提及
self
- 我包含此内容是因为它是确保您的 this 实际上是您想要的内容的标准方法。I think you're trying to get the value of the member and going about it the wrong way so try this:
To explain: the loop check first if the property is a user defined property as opposed to being inherited from the Object object. It also checks that the member is not a function (like validate()) it then alerts the value of the member.
The hasownproperty check is recommended by Douglas Crockford (father of JS) as best practice when iterating over memebers.
Hope this helps,
Darko
EDIT: Forgot to mention
self
- i included this because its the standard way of making sure that your this is actually what you want it to be.