We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi! Have the following questions. I need do define a function that will change one parameter of an abject:
this.setCoordinates (coordX, coordY) = function () {
this.location.x = coordX - this.location.x;
this.location.y = coordY - this.location.y;
}
Above is the piece of code. CoordX and coordY will be sent to the object this way. What is the correct syntaxis?
Answers
Not sure this is needed. This is the whole obeject:
}
And this is how I change the parameteres:
this.setCoordinates(coordX, coordY) = function () {};
, you're not defining a function!function
:https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
function (coordX, coordY) {}
this.setCoordinates = function (coordX, coordY) {};
WaterRock.prototype.setCoordinates = function (coordX, coordY) {};
class
keyword: \m/https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
Still don't fully get it. 1) Isn't this EXACTLY waht they do here? https://p5js.org/examples/objects-objects-2.html
initializing a function - as a method? this.move = function(posX, posY, damping)
2) Also, as for this ECMAScript 6, do you think it can be used in Openprocessing.org?
3) Rather, define them all outside the constructor function, annexing each method to its class' prototype, like this - is there a reference for that anywhere?
Thank you in advance.
1) Compare their
this.move = function (posX, posY, damping) {};
to your
this.setCoordinates(coordX, coordY) = function () {};
.They're clearly different! Your version is attempting to call setCoordinates() instead of defining it! b-(
Remember, we define functions/methods via keyword
function
. :-BThen later we suffix the operator
()
after its name in order to invoke it. *-:)Ok, what if i change it to: this.setCoordinates= function (coordX, coordY) {};
It will work for sure, but you still say it is not a good way, right?
2) Our JS code depends on the VM version running it, not the server hosting it. ;;)
3) That's called Prototype Pattern: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Prototype-based_programming
Take a look below on how methods should be defined using this ancient pattern:
https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_methods
Repeating again, forget about it. Just embrace the modern ES6 keyword
class
:https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
That's much easier. Especially for us coming from Java! ~O)
Ok, I will. Thank you!