简体   繁体   中英

How to add in a method to a javascript class?

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM