我是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"
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 changecar1.make
.changemak
needs to take theCar
as a parameter, and set the property of it.