javascript - 在定义函数之前使用它如何有效?

标签 javascript node.js

下面是 Node url 模块源代码的片段。

var punycode = require('punycode');
var util = require('util');

exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;

exports.Url = Url;

function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.host = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.query = null;
  this.pathname = null;
  this.path = null;
  this.href = null;
}

如您所见,“Url”在定义函数“Url”之前使用。 据我所知,这不是有效的 JavaScript,但它可以正常工作。

有人可以告诉我为什么这样可以吗?为什么 Node 编写者喜欢这个约定?

编辑:谢谢。我对“函数提升”不了解,因为之前的标题是错误的问题,已修改。

最佳答案

像“function a(){}”这样的函数将首先定义,即使它放在后面。 像“var a = function(){}”这样的函数将被定义为正常的变量定义顺序。 检查此代码:

alert(a);
function a(){}

alert(b);
var b = function(){}

http://jsfiddle.net/j4v7E/

关于javascript - 在定义函数之前使用它如何有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615225/

相关文章:

javascript - 了解 .map 和 Stringify 与对象

javascript - 无法查询 Puppeteer 上的选择器(TypeError : selector.startsWith 不是函数)

node.js - 未找到 FFmpeg/avconv

javascript - 机器人不会在直线中自行发送欢迎消息

javascript - 计算区域中的行数和列数

javascript - 自匿名函数在加载时运行绑定(bind)事件

node.js - 与 Prisma 2 相关的多个过滤器

node.js - 如何在 Node.Js 中保存带有 .db 扩展名的 Sqlite3 数据库

node.js - 续写 TypeScript : How to use `createdAt` in scope's `where` condition if it is not as part of model's attributes?

javascript - 在 MVC 项目中,当下拉列表更改值时如何更新模型?