Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的类构造变量在声明后保持未定义状态?_Javascript_Node.js_Class - Fatal编程技术网

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

Javascript 为什么我的类构造变量在声明后保持未定义状态?,javascript,node.js,class,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(){

我有两种情况。第一个,当我将变量构造为
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 {}

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

你在第二节课上拼错了
构造函数。

构造函数(令牌,格式)
你拼错了
构造函数
除了@PatrickEvans的分析之外,你还有一个潜在的问题,那就是你的代码中有三个项目的名字是
标记
。const
、构造函数的参数和属性。使用唯一的名称几乎总是更好。Tyvm、@PatrickEvans,我不知道你知道我怎么错过了这么长时间。谢伊,我的观察能力不足。太好了!我花了45分钟看了这门课却没有看到。