首页 > 解决方案 > JS代码中构造函数或类的正确放置是什么?

问题描述

由于构造函数基本上是一个存储为副本的对象,因此它们似乎被视为变量,因为它们不能只是代码中的“任何地方”,例如函数?

所以它们基本上需要在调用构造函数的位置或代码中的原型之上,否则它们将是未定义的或未被发现的......

其他人可以为我确认情况确实如此吗?

谢谢!

标签: javascriptsortingvariablesconstructorprototype

解决方案


在 JavaScript 中,声明被提升,使代码执行,就好像这些声明实际上是写在其封闭范围的顶部一样。声明可以是变量声明或函数声明。正因为如此,您可以在物理上以一种看起来像是在声明之前使用某些东西的方式编写代码,但实际上,由于提升,您不是。

变量声明提升:

console.log(x); // undefined because x hasn't been initialized, but has been declared
var x = "test";
console.log(x); // "test" because the assignment has now been processed

console.log(y); // error because y has never been decalred

函数声明提升:

foo();  // "hello from foo" because the entire function declaration was hoisted.
 
function foo(){
  console.log("hello from foo");
}

没有提升,因此您必须在使用它们之前编写它们。

类提升尝试:

const p = new Rectangle(); // ReferenceError

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

真的就是这么简单。


推荐阅读