Answer the question
In order to leave comments, you need to log in
How to create an overloaded class constructor in JS?
It's likely that I'm trying to do something that goes against the concept of JS. Therefore, if it is wrong to use overloads, please advise what needs to be done in this case.
Right now I'm writing simple wrapper classes for drawing shapes on canvas. For example, I want to make drawing a circle more convenient, for this you can skip a few parameters (or add, in the case of other classes).
In the original, drawing a colored circle looks like this:
context.arc(x, y, radius, startDegrees, endDegrees, counterClockwise);
context.fillStyle = '#FF0';
context.fill();
var circle = new Circle(x, y, radius, '#FF0');
var circle = new Circle(x, y, radius, '#FF0', startDegrees, endDegrees, counterClockwise);
Answer the question
In order to leave comments, you need to log in
In your case, just write...
function Circle(x, y, radius, color, startDegrees, endDegrees, counterClockwise)
{
}
If you do not pass the required number of parameters, then the unused ones will become undefined. function Circle(options)
{
}
new Circle({ radius: 10, x: 40, y: 30 });
new Circle radius: 10, x: 40, y: 30
Why do you need a circle object? What are you going to do with it then, why is it created here? Maybe it's easier to write just some kind of "helper":
helpers.circle = function (context, x, y, radius, color) {
context.arc(x, y, radius, startDegrees, endDegrees, counterClockwise);
context.fillStyle = color;
context.fill();
}
function Painter(context, defaultColor) {
this.context = context;
this.defaultColor = defaultColor;
this.circle = function (x, y, r, color) {
if (color === undefined) {
color = this.defaultColor;
}
this.context.arc(x, .... // code
}
}
function Circle(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.render = function (context) {
context.arc(this.x, ...
}
}
You have a very strange (mis)understanding of OOP, writing drawing code in the object constructor is like drug addiction. In general, writing any complex code in a constructor is a bad idea. If you want to draw a circle, make the drawCircle(...) method
Then. what you are asking in the question is not called function overloading (you can't do such things in javascript), but default argument values. To do this, we use the fact that the non-passed argument is undefined:
function (arg1, arg2, arg3) {
arg2 = arg2 || ten; // default
value arg3 = arg3 || 20;
…
}
As you can see, it turned out not difficult at all!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question