0

Below is a snippet from node url module source.

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

As you can see, the 'Url' is used before function 'Url' was defined. As far as I know this is not valid javascript, but it works ok.

Can someone tell me why this is ok? And why node writers love this convention?

EDIT : Thanks. I had no understanding of 'function hoisting' because the former title was the wrong question, modified.

Illidanek
  • 996
  • 1
  • 18
  • 32
  • 1
    function declerations are always hoisted to the top of the scope in javascript, so it's perfectly valid. – adeneo Jul 07 '14 at 16:20
  • http://designpepper.com/blog/drips/variable-and-function-hoisting ... if it was not valid, no one would write code like that. Since it works, it must be valid. – Felix Kling Jul 07 '14 at 16:23

1 Answers1

1

function like 'function a(){}' will be defined first even it's placed behind. function like 'var a = function(){}' will be defined as the normal variable define order. check this code:

alert(a);
function a(){}

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

http://jsfiddle.net/j4v7E/

TomWan
  • 319
  • 2
  • 9