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
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;
}
}
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
581 PHP ssh2_scp_send fails to send files as intended
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
618 Uncaught (inpromise) Error on Electron: An object could not be cloned
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.