changeColor()不是函数

问题描述 投票:0回答:2

为什么我在设置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();
javascript node.js
2个回答
0
投票

更改调用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语句。


0
投票

您需要将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();
© www.soinside.com 2019 - 2024. All rights reserved.