为什么当我定义和描述对象的方法时我的程序不起作用 卡车.drive()



我对下面这段代码有疑问,它抛出了一个类似语法错误的错误,但是我遵循的指南说语法是正确的。不知道该怎么做,没听懂,请帮忙。

代码链接:

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初始化之后,而不是在对象字面值内。

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

相关内容

  • 没有找到相关文章