1

I'm very new in JS And i get stuck with simple(?) problem about Classes

All i need to do is just to put some string into code to make assert expression valid

class Rec {
    constructor() {
        let a = 0;
        this['put here'] = () => a+++a;
    }
}

let inst = new Rec();
console.assert(
    inst == 1 && inst == 3 && inst == 5
);

Noticed the Class has endless chain of values like

__proto__:
    constructor:
       prototype:
          constructor:
             prototype:
                ...etc

so I've tried to use __proto__ but got a Function.prototype.toString requires that 'this' be a Function error.

1 Answer 1

2

You can use valueOf or toString

class Rec {
    constructor() {
        let a = 0;
        this['valueOf'] = () => a+++a;
    }
}

let inst = new Rec();
console.log(
    inst == 1 && inst == 3 && inst == 5
);

This works because of Abstract Equality Comparison between an object(inst) and a number

From the specification,

For the comparison x == y

  1. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

The ToPrimitive for an object calls the valueOf method if the hint is Number.

If you expand the expression, it looks like this: a++ + a. Every time inst is compared, valueOf method is called. And the sum of a++ and a is returned.

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

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.