-1

I have a class as follows:

// A validator class for strings
class StringValidation {
    type = "string";

    max(maximum = 255) {
        this.maximum = maximum;
        return this;
    }

    min(minimum = 1) {
        this.minimum = minimum;
        return this;
    }
}

// I then build the object
const string = new StringValidation();

// When I stringify the string objects after calling the object methods
// I get `{"type":"string","maximum":10,"minimum":5}`
console.log(JSON.stringify(string.max(10).min(5)));

// When I log the keys of the object
// I get `["type","maximum","minimum"]`
console.log(Object.keys(string.max(10).min(5)));

When I stringify the instance of class or print it's keys, I don't get max and min methods in the output.

This behaviour is quite confusing to me. Could anybody explain why did I get these results and why min & max methods seem to disappear.

codedump
  • 335
  • 3
  • 12
  • 3
    There's no `function` data type in JSON. (*goes hunting duplicates*) – Quentin May 23 '22 at 09:04
  • 1
    Please be aware that JSON is not JavaScript. – evolutionxbox May 23 '22 at 09:12
  • Yes I got to know about the behaviour of JSON from linked question. But what about output of `Object.keys` @Quentin and @evolutionbox – codedump May 23 '22 at 09:15
  • 3
    ["Object.keys() method returns an array of a given object's own enumerable property names"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) The class functions `max` and `min` are not "own properties". They live on the class's `prototype`. – spender May 23 '22 at 09:19
  • Ok, I have another question. As per the behaviour of the class in question, are following `userSchema` & `anotherUserSchema` strictly equivalent to each other? `const userSchema = {name: string.max(10).min(5)}` `const anotherUserSchema = {name: { type: "string", maximum:10, minimum:5}}` @spender – codedump May 23 '22 at 09:29
  • Define "strictly equivalent". Strictly equal? No. Structurally equal? Apparently yes, although the `name` prop of your second example will have a different prototype to the `name` prop of the first. – spender May 23 '22 at 09:36
  • Thanks that was a great help. What I'm worried about is that, if I use the class based example instead of a object as in above comment, then my `schema` objects will have unnecessary properties. I guess that's not the case somehow?? – codedump May 23 '22 at 09:52

0 Answers0