user81993
user81993

Reputation: 6609

Is there a way to define implicit conversion operators in javascript?

I have this class:

var color = function(r, g, b, a) {
    this.r = r
    this.g = g;
    this.b = b;
    this.a = a;

    this.toString = function() {
        if (!isset(a)) return "rgb("+parseInt(r)+","+parseInt(g)+","+parseInt(b)+")";
        return "rgba("+parseInt(r)+","+parseInt(g)+","+parseInt(b)+","+a+")";
    }
}

If i want the string output I have to type (for example) console.log(colorInstance.toString())

but is there a way to make the toString() method be called implicitly each time the receiving function expects a string value? So I could write console.log(colorInstance) instead?

Upvotes: 0

Views: 358

Answers (3)

user663031
user663031

Reputation:

toString will not be invoked when you simply pass the object to console.log. It (or valueOf) is invoked only in contexts where coercion to a primitive is required.

If this is really an issue for you, you could write your own version of console.log:

var logValue(...args) {
  console.log(...args.apply(a => a.toString()));
}

Or equivalent non-ES6 version.

Upvotes: 0

Oliver
Oliver

Reputation: 4091

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected.

From here. This applies to cases like "" + color, but otherwise, there aren't many cases where toString() gets implicitly called.

Upvotes: 3

Olavi Sau
Olavi Sau

Reputation: 1649

There is no way to define operators in javascript, at best you could make some odd functions. However javascript also has automatic type conversion, so if the runtime expects a string javascript will actually always call the toString method. There is explicit casting such as parseInt(value) though :)

Upvotes: 0

Related Questions