Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

Order of hoisting in JavaScript

function g () {
    var x;
    function y () {};
    var z;
}

I would like to know exactly what order the above code becomes when hoisted.

Theory 1: Order between vars and functions remains as-is:

function g () {
    var x;
    function y () {};
    var z;
}

Theory 2: vars come before functions:

function g () {
    var x;
    var z;
    function y () {};
}

Theory 3: functions come before vars:

function g () {
    function y () {};
    var x;
    var z;
}

Which theory is correct?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Functions are hoisted first, then variable declarations, per ECMAScript 5, section 10.5 which specifies how hoisting happens:

We first have step 5 handling function declarations:

For each FunctionDeclaration f in code, in source text order do...

Then step 8 handles var declarations:

For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do...

So, functions are given higher priority than var statements, since the later var statements cannot overwrite a previously-handled function declaration. (Substep 8c enforces the condition "If?varAlreadyDeclared?is?false, then [continue...]" so extant variable bindings are not overwritten.)

You can also see this experimentally:

function f(){}
var f;
console.log(f);

var g;
function g(){}
console.log(g);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...