javascript文字初始化循环
我有一个对象,它有几个在创建对象时设置的属性。
这个对象最近更改为对象文字表示法,但我遇到了一些在网上搜索没有揭示的问题。
简单地说,我需要这样做:
Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
var self = {
id: _id,
// other properties
links: [],
for (var i=0,j=0;i<8;i++) { //<- doesn't like this line
var k = parseInt(_links[i]);
if (k > 0) {
this.links[j++] = k;
}
},
// other methods
};
return self;
};
如何以对象文字表示法初始化构造函数中的属性?
I have an object which has several properties that are set when the object is created.
This object recently changed to object literal notation, but I've hit a bit of a problem that searching on the net doesn't reveal.
Simply stated I need to do this:
Star = function(_id, _x, _y, _n, _o, _im, _c, _b, _links) {
var self = {
id: _id,
// other properties
links: [],
for (var i=0,j=0;i<8;i++) { //<- doesn't like this line
var k = parseInt(_links[i]);
if (k > 0) {
this.links[j++] = k;
}
},
// other methods
};
return self;
};
How do I initialise a property in the constructor in object literal notation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用匿名函数动态创建数组:
您可以在定义文字后执行此操作:
You can create the array on the fly using an anonymous function:
You can do it after the literal is defined:
对于这个特定的示例,您可以使用匿名函数,如下所示:
For this specific example, you could use an anonymous function, like this:
你不能。对象表示法不允许这样做。但是,您可以在初始化对象后添加属性。
顺便说一下,
self
已经是一个已定义的对象,它是 window 对象的别名。当您定义一个名为 self 的临时对象时[因此,您没有摆脱 window.self],这不是您应该做的事情。就好像self
是一个关键字,而您当前对它的使用是非法的。You can't. Object notation doesn't allow this. However, you can add the properties AFTER initializing your object.
By the way,
self
is a defined object already, which is an alias for the window object. While you ARE defining a temporary object named self [and thus, you aren't getting rid of window.self] this isn't something you shold be doing. Act as ifself
was a keyword and your current usage of it is illegal.