你能发现这段 JavaScript 代码中的 3 个 Bug 吗?

问题描述 投票:0回答:3
// 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()

我的在线作业遇到问题。 我不太熟悉使用类的构造函数,所以我找不到语法有什么问题。

  1. 到目前为止,我只发现使用“const”作为 1 个错误,因为这触发了“分配给常量变量”错误。
javascript html debugging syntax constructor
3个回答
1
投票

您遇到的三个错误:

  • 首先,将
    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!


1
投票

第一个错误是第9行而不是

const greeting = this.greeting
应该是
let greeting = this.greeting

第二个错误是第14行而不是

if (greeting = undefined)
应该是
if (greeting == undefined)

第三个错误是第18行而不是

return "${greeting}, ${name}!";
应该是
return 
${greeting}, ${name}!`;


0
投票

代码的简洁版本:

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());
© www.soinside.com 2019 - 2024. All rights reserved.