我将如何设置一种方法来更新 JavaScript 对象的传递属性?

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

我想为一个对象创建一个方法来只更新传递的属性。

例如

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

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

如果我这样做 Car.update({color:'red'}) 我想更新对象但不覆盖品牌。我想使用 Object.assign(this, o) 之类的东西,但不确定如何分配它。我需要创建原型吗? Car.prototype.update = ?

const object1 = {
color : 'red'
};

const obj2 = Object.assign({color: 'blue', d: 5}, object1);
console.log(obj2.color); // red

Object.assign() 方法 -> 复制所有可枚举自身属性的值。 最后它将return目标对象

您在 OP 中提出的想法很有效。

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

  this.update = function (o) {
 Object.assign(this, o);
  }
}

a = new Car();
a.update({color: "red"});
console.log(a.color + " - " + a.brand + " - " + a.key);
// returns "red - bmw - 0"

Object.assign 改变了第一个参数,因此不需要将 Object.assign() 的结果分配给某些东西。

Object.assign(this, o);

...将正常工作。

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);