Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Create setter dynamically?

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>  

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!