为什么我在设置getCar()
的changeColor()
功能中出现错误?
function Car(model, color, price) {
this.model = model;
this.color = color;
this.price = price;
this.changeColor = function() {
console.log(this);
this.color = 'Blue';
};
this.getCar = function() {
changeColor();
return console.log(`Model: ${this.model} Color: ${this.color} Price: ${this.price}`);
};
}
const mitsubishi = new Car('Mitsubishi', 'Black', 1991);
mitsubishi.getCar();
更改调用changeColor()
的方式。
更改:
this.getCar = function() {
changeColor()
console.log(`Model: ${this.model} Color: ${this.color} Price: ${this.price}` )
}
至:
this.getCar = function() {
this.changeColor()
console.log(`Model: ${this.model} Color: ${this.color} Price: ${this.price}` )
}
请注意,我删除了return
语句。
您需要将changeColor()
更改为this.changeColor()
。
function Car(model, color, price) {
this.model = model
this.color = color
this.price = price
this.changeColor = function(){
//console.log(this)
this.color = 'Blue'
}
this.getCar = function() {
this.changeColor()
return console.log(`Model: ${this.model} Color: ${this.color} Price: ${this.price}` )
}
}
const myCar = new Car("Ford", "Orange", "10,000");
console.log("Original Car:");
console.log(myCar.model, myCar.color, myCar.price)
console.log("\nmyCar.getCar():");
myCar.getCar();