0

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?

2
  • 2
    something like: ""+color Commented Oct 25, 2015 at 8:21
  • I guess you are looking for valueOf. Commented Oct 25, 2015 at 8:49

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.