我對以下代碼有疑問,它會引發類似語法錯誤的錯誤,但我遵循的指南說語法是正確的。不知道怎么辦,沒看懂,請幫忙。
這是代碼鏈接:
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() {
uj5u.com熱心網友回復:
你可能誤讀了。等效代碼為:
// 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,而不是在物件字面量內。
首先,您不能將賦值放在物件文字中,只能放在屬性宣告中。其次,在賦值完成之前,您不能參考正在定義的變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/468395.html
標籤:javascript 语法错误
