Search code examples
javascriptobjectmethodsprototype

How would I set up a method to update passed properties of JavaScript object?


I'm looking to create a method for an object to update only the properties that are passed.

for example

function Car () {
  this.color = 'yellow'
  this.brand = 'bmw'
  this.key = 0

  this.update = function (o) {
    this.key++
    // maybe Object.assign(this, o) somehow ??
  }
}

If I do Car.update({color:'red'}) I want to update the object but not overwrite the brand. I want to use something like Object.assign(this, o) but not sure how to assign it. Do I need to create a prototype? Car.prototype.update = ?


Solution

  • Object.assign mutates the first argument, so there is no need to assign the result of Object.assign() to something.

    Object.assign(this, o);
    

    ...will work fine.

    function Car () {
      this.color = 'yellow'
      this.brand = 'bmw'
      this.key = 0
    
      this.update = function (o) {
        this.key++
        Object.assign(this, o);
      }
    }
    
    var car = new Car();
    car.update({color: 'red'});
    console.log(car);