javascript - JS代码中构造函数或类的正确放置是什么?
问题描述
由于构造函数基本上是一个存储为副本的对象,因此它们似乎被视为变量,因为它们不能只是代码中的“任何地方”,例如函数?
所以它们基本上需要在调用构造函数的位置或代码中的原型之上,否则它们将是未定义的或未被发现的......
其他人可以为我确认情况确实如此吗?
谢谢!
解决方案
在 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;
}
}
真的就是这么简单。
推荐阅读
- sql - 在同一个表中查找从先前保存中删除的行的保存 ID
- rtf - 如何使用 RTF 在 BI Publisher 中根据特定单词过滤值
- sql - 仅更新内容以在字段中添加其他文本。SQL
- r - 有没有办法让用户在 R Shiny 应用程序中上传图像并将其呈现在可下载的降价报告中?
- perforce - 创建工作区时 Perforce 添加的“仓库”文件夹
- r - 如何使用 ggplot 绘制条形图
- c++ - 扫雷程序,意外输出
- google-sheets - 如何根据不同的文本字段进行计算?
- oracle - 如何在 apex oracle 应用程序中启用功能
- javascript - 浏览器中 JS、HTML、CSS 的执行顺序?