Making a setter in js

Hello.

I’m struggling with some simple stuff. I think…

I have my object, an instance of a class. I’m trying to make one set() function that would get a indefined number of args, based on that I’d like to change some properties.
I’m trying something like this:

class Class{
    constructor(prop1, prop2){
        this.prop1 = prop1;
        this.prop2 = prop2;
        this.prop3 = "otherstuff"
    }
}

I’d like to have something like:

// inside the class
set(...props){}

and call in a way that I can pass a pair of prop name: value and change that one. I’m almost there… but I’m not sure how to make it happen. Whats the best way? Should I pass an array of arrays? An array of objects? what? And how can I call this when reading the values

//in main sketch
    page.set([['prop1', 6][prop2, 6]]);  //? or
    page.set([{'prop1': 6}, {'prop2': 6}]); // or what :)

//inside class 

    set(...all) {
            for (const prop of all) {
                const n = [prop]; // logging this is ok i get the name
                const v = prop;  // logging this is ok i get the value
                this.n = v;// here it does not work, the this.prop1 never get the value
            }
            this.init();
        } 

I’m used to numbers indexed arrays, but this seems to be a case to use the string as index, I mean… how should i do it? The instance itself have some kind of properties array, right? How can I use the string to access it?

thanks

1 Like

Just 1 single object containing 1 or more { key: value } pairs is enough.

And in order to check for each passed { key: value } pair actually exists within the class instance we can use a for ( in ) loop to iterate over the passed object and then conditionally assign its value to the corresponding class property via operator &&=:

class SomeClass {
  constructor(prop1, prop2, prop3 = 'Same Stuff') {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.prop3 = prop3;
  }

  setProps(props) {
    for (const p in props)  this[p] &&= props[p];
    return this;
  }
}

const a = new SomeClass(10, 200);
console.log(a); // SomeClass {prop1: 10, prop2: 200, prop3: "Same Stuff"}

a.setProps({ prop3: 'Other Stuff', prop1: -50 });
console.log(a); // SomeClass {prop1: -50, prop2: 200, prop3: "Other Stuff"}

a.setProps({ prop10: 'Invalid Property' });
console.log(a); // SomeClass {prop1: -50, prop2: 200, prop3: "Other Stuff"}
5 Likes

Great!!! Thanks a lot. Now I’ll read the pointed link to understand how that works.
Amazing!
cheers

edit: I see, makes sense… And also it’s needed to return the assigned property, right?

Nope! return this; is merely an extra that makes a method chain-callable.
Also notice the return this; statement doesn’t belong to the for..in loop block.

I see, ok thanks again.

1 Like

Worked like a charm :))))