如何确保我的对象具有自己的x和y

时间:2018-12-18 12:27:24

标签: javascript p5.js

我猜测互联网上某个地方可能对此有一个答案,但我找不到它。我在制作图形计算器,并试图使“曲线图”遵循某个函数y = 2x。虽然我似乎无法找出如何使图具有自己的x和y(它们唯一的x和y)。

function CreateDot() {
this.ix = 1; //this is the x value of the function and is also used in y = 2x
this.fy = this.ix * 2; //this is the y value of the funciton y = 2x

    this.newDot = function() {
//this is defining the x value of the plot and scaling the value to have it follow the grid
        this.x1 = spacing * this.ix;


// this is defining the y value of the plot and scaling the value to have it follow the grid
        this.y1 = 500 - spacing * this.fy; //


//this is the code for creating the "plot" which is a dot on the screen and red in colour
        stroke(255,0,0);
        strokeWeight(25);

//this is defining the position of the point with the values above x1 and y1
        point(this.x1,this.y1);


//this is supposed to allow the next value of x=2 in the function y = 2x and so allowing the next coordinates of the plot to be ( 2, 4 ) and the next dot (3, 6) and so on.
        this.ix = this.ix + 1;
}
}

我注意到的是,在我将此函数构造为一个函数并将新的点放入数组并将其限制为5之后,我运行了它,一个点一直向右飞。我打印了每个对象x和y,它们具有相同的值。

所以我的问题是如何确保每个对象都有自己唯一的x和y值?

谢谢!

1 个答案:

答案 0 :(得分:3)

您必须将函数放在原型上并以这种方式调用,或者必须将点作为参数传递给更新函数:

//	Prototype
function CreateDot( spacing ) {
  this.ix = 1;
  this.fy = this.ix * 2;
  this.x1 = spacing * this.ix;
  this.y1 = 500 - spacing * this.fy;
}
CreateDot.prototype.addOne = function() {
  // this refers to: 'the dot you call addOne upon'.
  this.ix = this.ix + 1;
};
var myDot = new CreateDot( 250 );
console.log( 'before myDot.addOne() : ' + myDot.ix );
myDot.addOne();
  console.log( 'after myDot.addOne() : ' + myDot.ix );
//	Seperate function
var addOne_f = function( dot ) {
  // this refers to 'the window instance', so you need to use the 'dot' parameter to refer to the dot.
  dot.ix = dot.ix + 1;
};
console.log( 'before addOne_f( myDot ) : ' + myDot.ix );
addOne_f( myDot );
console.log( 'after addOne_f( myDot ) : ' + myDot.ix );

//  Inside an array:
var dots = [
  new CreateDot( 200 ),
  new CreateDot( 225 ),
  new CreateDot( 250 )
];
//  Update all dots
dots.forEach( dot => dot.addOne());
//  Update the second dot again to show they're not linked
dots[ 1 ].addOne();
console.log( dots.map( dot => dot.ix ));