0

How could I put setPosition inside of the class DrawClockHand? Is DrawCLockHand even a class technically in Javascript.

Code:

var DrawClockHand = function(cv) {
    this._cv = cv;
    this._ctx = cv.getContext('2d');
    this.TIME = 1000;
    this._r = 50;
}

DrawClockHand.prototype.setPosition = function(x,y) {
    x = x || 0;
    y = y || 0;
    this._x = x;
    this._y = y;
}
Tim
  • 2,121
  • 2
  • 20
  • 30
  • Do you mean as a function on an instance of an object created by the constructor function `DrawClockHand` as opposed to on the prototype as you have above? – Russ Cam Aug 30 '14 at 20:58
  • 2
    *DrawClockHand* is a function. If called with *new*, if behaves as a constructor. There are no classes in ECMAScript (but [*ES6*](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-class-definitions) would like to change that). – RobG Aug 30 '14 at 21:03
  • Yes, on reply one. If I want to make this into a class how would I go about doing that. ECMAScript is that another form of Javascript. –  Aug 30 '14 at 21:07
  • possible duplicate of [JavaScript: Class.method vs. Class.prototype.method](http://stackoverflow.com/questions/1635116/javascript-class-method-vs-class-prototype-method) – Whymarrh Aug 30 '14 at 21:17

1 Answers1

5

DrawClockHand is not a class, it is just a function that creates an object with a given structure (if called with the new operator).

If you call the DrawClockHand function like this:

var o = new DrawClockHand(someVal);

Then you will be creating a new object with the structure established by the DrawClockHand function. In that case, in the o object will also have the setPosition method because it was set as a DrawClockHand's propotype property.

So this is valid

var o = new DrawClockHand(someVal);
o.setPosition(1,2);
Augusto Altman Quaranta
  • 1,526
  • 1
  • 21
  • 32
  • is this a good way of doing it. Or should I have created a real class with real constructors in Javascript. I am somewhat new to the Javascript aspect of things. –  Aug 30 '14 at 21:18
  • First of all, when you code javascript stop thinking in classes. A class defines a static data structure (including methods), and javascript was designed to be a very dynamic language. Nevertheless there are lots of cases where you may want to define a concrete strcuture for a set of differents objects, in that cases you should use a creational pattern. One creational pattern is the exposed in my answer where you have a function that defines the strcture and creates the object with that given structure. – Augusto Altman Quaranta Aug 30 '14 at 21:25
  • I strongly recomend you this readings: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript http://dmitrysoshnikov.com/tag/ecma-262-3/ http://leoasis.github.io/posts/2013/01/24/javascript-object-creation-patterns/ – Augusto Altman Quaranta Aug 30 '14 at 21:27