// This class takes a name string and greeting string in
// the constructor. Here are some examples of how this should work:
//
// g = new Greeter()
// g.greet() # => "Hello, Anonymous!"
//
// g = new Greeter("What's up", "Dog")
// g.greet() # => "What's up, Dog!"
//
// g = new Greeter("Hola")
// g.greet() # => "Hola, Anonymous!"
// Unfortunately, this code isn't quite working.
// Can you spot at least 2 bugs?
class Greeter {
constructor(name, greeting) {
this.name = name;
this.greeting = greeting;
}
greet() {
const name = this.name;
const greeting = this.greeting;
if (!name) {
name = "Anonymous";
}
if (greeting = undefined) {
greeting = "Hello";
}
return "${greeting}, ${name}!";
}
}
g = new Greeter("Hi")
g.greet()
我的在线作业遇到问题。 我不太熟悉使用类的构造函数,所以我找不到语法有什么问题。
您遇到的三个错误:
const
更改为let
double quotes
class Greeter {
constructor(name, greeting) {
this.name = name;
this.greeting = greeting;
}
greet() {
//1
let name = this.name;
let greeting = this.greeting;
if (!name) {
name = "Anonymous";
}
if (greeting == undefined) {
//2
greeting = "Hello";
}
return `${greeting}, ${name}!`; //3
}
}
g = new Greeter("Hi");
g.greet(); //Hello, Hi!
第一个错误是第9行而不是
const greeting = this.greeting
应该是let greeting = this.greeting
第二个错误是第14行而不是
if (greeting = undefined)
应该是if (greeting == undefined)
第三个错误是第18行而不是
return "${greeting}, ${name}!";
应该是return
${greeting}, ${name}!`;
代码的简洁版本:
class Greeter {
constructor(name = 'Anonymous', greeting = 'Hello') {
this.name = name;
this.greeting = greeting;
}
greet() {
return `${this.greeting}, ${this.name}!`;
}
}
const g = new Greeter(undefined, 'Hi');
console.log(g.greet());