簡體   English   中英

如何確保我的對象具有自己的x和y

[英]How to make sure my object has their own x and y

我猜想互聯網上某個地方可能對此有一個答案,但我找不到它。 我在制作圖形計算器,並試圖使“曲線圖”遵循某個函數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值?

提前致謝!

您必須將函數放在原型上並以這種方式調用,或者必須將點作為參數傳遞給update函數:

 // 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 )); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM