JavaScript-更改调用的参数后,更新Class中Instance的值

我是JS和OOPS的新手(也不知道标题)。

在下面的代码段中,包含Car类及其实例。我想问一下在更改一个类参数后是否有一种更新实例的方法。例如,在更改参数后,我希望将预期输出更改为更新后的值,即NewEagl。 下面的代码两次都返回(“ Eagle”)。

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

var mak = 'Eagle'
const car1 = new Car(mak, 'Talon TSi', 1993);

console.log(car1.make);
// output: "Eagle"
function changemak() {
    mak = 'NewEagl';
}

changemak();
console.log(car1.make);
// Expected output: "NewEagl"
评论
  • ousman
    ousman 回复

    When you assign a variable to a property, it just copies the value, it doesn't make a permanent link between the variable and the property. So changing mak doesn't change car1.make.

    changemak needs to take the Car as a parameter, and set the property of it.

    function changemak(car) {
        car.make = 'NewEagl';
    }
    changemak(car1);