下面是 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(){}
关于javascript - 在定义函数之前使用它如何有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615225/