我的代码中是否有任何错误esp var newpoint [0] = new Point; .我想知道如何在javascript中做oop
function Point()
{
var x;
var y;
}
var length = 1;
var arrayindex;
var newpoint[0] = new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
newpoint[length].x = 10*i;
newpoint[length++].y = 10*i;
}
for(arrayindex in newpoint )
{
alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
Run Code Online (Sandbox Code Playgroud)
编辑:谢谢大家.我想出了两个代码,需要知道哪一个更好,任何sugesstion和protips.都工作
function Point()
{
this.x;
this. y;
}
var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
newpoint[length] =new Point();
newpoint[length].x = 10*i;
newpoint[length++].y = 10*i;
}
for(arrayindex in newpoint )
{
alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
Run Code Online (Sandbox Code Playgroud)
和
var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
newpoint[length] = {};
newpoint[length].x = 10*i;
newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
Run Code Online (Sandbox Code Playgroud)
在我评论您的代码之前,请阅读教程:https://developer.mozilla.org/en/JavaScript/Guide
现在进行娱乐:
function Point()
{
var x; // great a local variable!
var y; // another one! they drop out of scope... (protip: use 'this')
}
var length = 1; // ???
var arrayindex; // better declare that in the for
var newpoint[0] = new Point; // that works yes, but only the `new Point` part, 'newpoint[0]' what is that supposed to do?
newpoint[0].x = 10; // there's no x property on a `Point` here
newpoint[0].y = 10;
for(i=0 ; i<10; i ++) // i leaks into global scope
{
newpoint[length].x = 10*i; // ??? Fails, newpoint is not an array
newpoint[length++].y = 10*i; // Again, what's the point of this?
}
for(arrayindex in newpoint ) // great! a extremely slow for in to iterate over an array..
// pro tip, this will enumerate over all the _properties_ of the _object_
{
// usual complain about the missing 'hasOwnProperty' call (TM)
alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
Run Code Online (Sandbox Code Playgroud)