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;
}
4
  • 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? Commented Aug 30, 2014 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 would like to change that). Commented Aug 30, 2014 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. Commented Aug 30, 2014 at 21:07
  • possible duplicate of JavaScript: Class.method vs. Class.prototype.method Commented Aug 30, 2014 at 21:17

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.