Search code examples
javascriptnew-operator

(JS) How to use the "new" operator and return something other than "this"?


I am making a JavaScript game framework. I have a function called Color3. I am trying to use the function using the new operator. However, every time it returns the object instead of the string I wanted to return. Here is the code:

Color3 = function(r, g, b) {
    this.r = 255;
    this.g = 255;
    this.b = 255;

    if (r != null)
        this.r = r;
    if (g != null)
        this.g = g;
    if (b != null)
        this.b = b;

    return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
};

var myColor = new Color3(0, 255, 0);
console.log(myColor);

Expected output:

"rgb(0, 255, 0)"

Actual output:

Color3 {r: 0, g: 255, b: 0}

Is there a way that I can get the expected output? Or do I have to not use the new operator?


Solution

  • If what you return is not an object, the default object is returned. You should return an object to change the return value. Try return new String("rgb(" + this.r + ", " + this.g + ", " + this.b + ")")