javascript - 为什么我的类构造变量在声明后保持未定义状态?

标签 javascript node.js class

我有两种情况。第一个,当我将变量构造为 constructor(var1, var2){this.var1 = var1; this.var2 = var2 时,它们在类的其余部分中未定义,例如 test(){console.log(this.var1)} 。在另一个中,它记录正​​确的值。

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  test(){
    console.log(this)
  }
}
const p = new Rectangle(100, 200)

p.test() // => Rectangle { height: 100, width: 200 }

const token = "aaa"
class CatApi {
  constuctor(token, format) { // only xml, html and src; src gives link in response.location header
    this.token = token
    if (format) {
      this.format = format // string allowing xml, html, src and json; default is json
    } else {
      this.format = 'json'
    }

  }
  test(){
    console.log(this)
  }
}
const cat = new CatApi(token, 'json')
cat.test() // => CatApi {}

发生了什么事?我做错了什么?

最佳答案

您在第二个类中拼错了构造函数

关于javascript - 为什么我的类构造变量在声明后保持未定义状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42637175/

相关文章:

node.js - 如何在express中对api进行分组

node.js - 使用 cURL CLI 的 HTTPS POST 到 NodeJS 服务器

c++ - 声明变量时 : variable not declared in this scope

javascript - 如何验证 g-captcha-response?

javascript - 使用 Perl 或 Python 进行 Hacky 文档网站搜索

JavaScript 图像 URL

javascript - 迭代用户选项并将它们分配给 CoffeeScript 中的对象实例

php - 避免两次打开同一页面

javascript - 如何使用 axios 在 POST 请求上传递唯一的属性值?

c# - Activator.CreateInstance() 的麻烦