为什么当我定义和描述一个对象的方法时我的程序不工作 truck.drive()

why my program doesn't work when i define and describe the method of an object truck.drive()

我对下面的代码有疑问,它会抛出语法错误之类的错误,但我遵循的指南说语法是正确的。不知道怎么办,没看懂,求助

这里是代码link:

const car = {
    maker: 'Ford',
    model: 'Fiesta',
  
    drive() {
      console.log(`Driving a ${this.maker} ${this.model} car!`)
    }
  }

car.drive()

// the same above code can be written as:
const bus = {
    maker: 'Ford',
    model: 'Bussie',
  
    drive: function() {
      console.log(`Driving a ${this.maker} ${this.model} bus!`)
    }
  }

bus.drive()

// the same code above can be written in this way:
const truck = {
    maker: 'Tata',
    model: 'Truckie',
  
    truck.drive = function() {
      console.log(`Driving a ${this.maker} ${this.model} truck!`)
    }
  }

truck.drive()

// Now, let us see how the arror function works:
const bike = {
    maker: 'Honda',
    model: 'Unicorn',
  
    drive: () => {
      console.log(`Driving a ${this.maker} ${this.model} bike!`)
    }
  }
  
bike.drive()

错误:

SyntaxError: Unexpected token '.'

at line: truck.drive = function() {

你可能看错了。等效代码为:

// the same code above can be written in this way:
const truck = {
  maker: 'Tata',
  model: 'Truckie'
}

truck.drive = function() {
  console.log(`Driving a ${this.maker} ${this.model} truck!`)
}

truck.drive的赋值是在truck的初始化之后,而不是在对象字面量内部。

首先,不能将赋值放在对象字面量中,只能放在 属性 声明中。其次,在赋值完成之前,您不能引用正在定义的变量。