ES6: How to change properties within a class

Asked 2 years ago, Updated 2 years ago, 69 views

The value of the property does not change to 5 in the code below:

class TestClass {

  constructor(prop){
    this.prop = prop;
    TestClass.validateProp(prop); // For example, prop must be an integer with a minimum value of 5.
    console.log (this.prop)
  }

  static validateProp(prop) {
    // Let's say this is illegal.
    This.prop = 5; // Set to Minimum
  }

}

let testInstance = new TestClass ('Invalid Value');

Maybe you need a getter setter.The number of examples on the Internet is small and often ends with a Getter Setter declaration.Based on the Post here, we added getters and setters to the above code, but the prop has not been set to 5.

class TestClass {

  constructor(prop){

    this.prop = prop;
    TestClass.validateProp(prop); // For example, the minimum value must be 5.
    console.log (this.prop)

  }

  set prop(newValue){
    this._prop = newValue;
  }

  getprop(){
    return this._prop;
  }

  static validateProp(prop) {
    // Let's say this is illegal.
    This.prop = 5; // Set to Minimum
  }
}

let testInstance = new TestClass ('Invalid Value');

What should I do?

(For the example above, the prescribed value is useful, but the center of this question is to change the properties in the class, so please place the prescribed value.)

javascript ecmascript-6 es6

2022-09-30 18:00

2 Answers

Any language that supports object-oriented programming cannot reference an instance from a static method.For the example in the question, the simplest solution is to make the validateProp method a non-static method:

class TestClass {

  constructor(prop){
    // By the way, using parameters and then validating them is a strange way of writing.
    this.prop = prop;
    This.validateProp(prop); 
  }

  validateProp(prop){
    // ...
    This.prop = 5;
  }
}

If you are particular about static methods:

class TestClass {

  constructor(prop){
        // It's working, but there are a lot of useless cords.
        if(!TestClass.isPropertyValid(prop)){
            prop=5;
        }
        this.prop = prop;
  }

  static isPropertyValid (prop) {
    return prop>=5;
  }
}

The simplest way to write this example:

class TestClass {
  constructor(prop){
        This.prop=prop>=5?prop:5;
  }
}


2022-09-30 18:00

If you use getter, setter, the problem is that there is no good way to share values (private property).

'use strcit';
const TestClass=(()=>{
  const wm = new WeakMap;

  US>return class TestClass {
    constructor(prop){
      wm.set(this,Object.create(null));
      this.prop = prop;
    }
    getprop(){
      return wm.get(this).prop;
    }
    set prop(prop){
      prop = Math.floor(prop);
      return wm.get(this).prop=prop<5?5:prop;
    }
  }
})();

const test = new TestClass(2);
console.log(test.prop);//5

Re: @Gurebu Bokofu


2022-09-30 18:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.