Search code examples
javascriptobjecttypesgetterprimitive

How can I create a object like a string, for example? A object with many properties, and a default console.log/evaluation value


I want to create a object with many properties, but, when I just console.log my object or insert it into a evaluation, it does have a default value to evaluate or log, a primitive value, like "test", for example.

I tried to use getters and setters but had no sucess.

const obj = { a: 'test1', b: 'test2' } // this is my object

console.log(obj.a); // this should return 'test1'

console.log(obj); // this should return a value of my choice, like 'testobj' or a number

'testobj' === obj; // should be true, since I want my obj to have a default value of 'testobj' in evaluations
// just like a primitive type, like strings or numbers. They have many functions and a default value

Solution

  • One year later I ran into this question again and found a solution. My objective was to create a string/number with a few methods that would use itself(this) to generate the output values and could be used in your code as a normal number/string without casting or anything like that, like a normal JS number/string.

    Something like a number that has its own value but you can access the number.negative property and you will have the negative equivalent to your number. You can do it creating a class that extends the primitive type that you want to use, like, for a Number, I can use:

    class Num extends Number {
      negative = this * (-1);
      // I can even add a few methods that receive props to calculate new output values
      exponential(exp) {
        let result = 1;
        while(exp-- > 0) {
          result *= this;
        }
        return result;
      }
    }
    
    const myNum = new Num(3);
    
    console.log('Simple sum: ', 1 + myNum); // outputs 4
    
    console.log('Negative: ', myNum.negative); // outputs -3
    
    console.log('Exponential: ', myNum.exponential(2)); // outputs 9

    The code above works for strings as well. Hope I can help someone with this.