JS 代码中构造函数或 类 的正确位置是什么?

What is the correct placement of constructors or classes in JS code?

由于构造函数基本上是一个存储为副本的对象,从某种意义上说,它们似乎被视为变量,因为它们在代码中不能只是 "Anywhere",例如函数?

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

其他人可以帮我确认一下确实是这样吗?

谢谢!

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

变量声明提升:

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");
}

Classes are not hoisted所以你必须在使用它们之前写下它们。

Class 提升尝试:

const p = new Rectangle(); // ReferenceError

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

就是这么简单

变量只是存储和引用值的一种方式。对象是一种值。函数是一种对象。构造函数是设计为使用 new 关键字调用的函数(它创建一个对象并在其上设置原型链)。

要调用构造函数,您需要有权访问该值。这可以通过一个变量(通常是)。

变量必须包含构造函数才能引用它。


函数声明是创建函数的一种手段,可以是构造函数,也就是提升,允许它在代码中较早使用然后出现。


但是,构造函数通常有许多方法添加到原型中,并且在下面的示例中没有提升这些方法:

  1. dog实例构建成功
  2. 吠叫尝试失败,因为尚未分配给 prototype.bark

var fido = new Dog("Fido");
fido.bark();

function Dog(name) {
    this.name = name;
}

Dog.protype.bark = function () {
    alert(`Woof! I'm ${this.name}`);
}