代码之家  ›  专栏  ›  技术社区  ›  Gourab Mahapatra

当我定义和描述对象卡车的方法时,为什么我的程序不工作。驱动器()

  •  -1
  • Gourab Mahapatra  · 技术社区  · 2 年前

    我对下面的代码有疑问,它会抛出一个类似语法错误的错误,但我遵循的指南说语法是正确的。不知道该怎么办,不明白,请帮忙。

    以下是代码链接:

    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() {
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Barmar 0___________    2 年前

    你可能误读了。等效代码为:

    // 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 ,而不是在对象文本中。

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