Home > other >  Create setter dynamically?
Create setter dynamically?

Time:11-13

Is there way to add setter to object dynamically like this?

output = document.querySelector(".output")
log = (out)=>{
  output.innerHTML = out
}

class A {
  constructor(some){
    this._some = some
  }    
}

myObj = new A(1)
// myObj = Add setter there...
<div class="output"></div>  
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I just need this to write classes which instaces can dynamically create setters to their properties.

CodePudding user response:

You can do it like this:

class A {
  constructor(some){
    this[some] = some // This needs to be a string, otherwise it doesn't work
  }    
}

If you need to do more complex stuff you can do something like:

const exampleInput = {
  prop1: 123,
  prop2: "someString"
}

class A {
  // Make some an object like the one above
  constructor(some){
    for (prop in some) {
       this[prop] = some[prop]
    }
  }    
}

Explanation on for...in loop

CodePudding user response:

Is this what you want?

class A {
  constructor(some){
    this._some = some
  }    
}

let myObj = new A(1)

console.log(myObj._some) // 1

Object.defineProperty(myObj, 'setSome', {
  set: function(x) { this._some = x ; }
});

myObj.setSome = 77;
console.log(myObj._some) // 77
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related