, JavaScript, OP .
,
JavaScript
JavaScript . , . Ive JavaScript, . , JavaScript , , C-. C:
#include <stdio.h>
int main() {
int x = 1;
printf("%d, ", x);
if (1) {
int x = 2;
printf("%d, ", x);
}
printf("%d\n", x);
}
1, 2, 1. , C C . , if, , . JavaScript. Firebug:
var x = 1;
console.log(x);
if (true) {
var x = 2;
console.log(x);
}
console.log(x);
Firebug 1, 2, 2. , JavaScript . C. , if, . .
, , C, ++, # Java, . , - JavaScript . , :
function foo() {
var x = 1;
if (x) {
(function () {
var x = 2;
}());
}
}
, , . , , JavaScript. . , , .
,
JavaScript :
Language-defined: this arguments.
Formal parameters: , .
- :
function foo() {}. - :
var foo;. - ( "" ) JavaScript.
- , , . , :
:
function foo() {
bar();
var x = 1;
}
:
function foo() {
var x;
bar();
x = 1;
}
, , , . :
function foo() {
if (false) {
var x = 1;
}
return;
var y = 1;
}
function foo() {
var x, y;
if (false) {
x = 1;
}
return;
y = 1;
}
, . . , . , . JavaScript:
function test() {
foo();
bar();
var foo = function () {
alert("this won't run!");
}
function bar() {
alert("this will run!");
}
}
test();
In this case, only the function declaration has its body raised at the top . The name "foo" is raised, but the body is left behind, which must be assigned at runtime.
This covers the basics of lifting. The full 100% credit of this answer corresponds to ben cherry . I do not want to post this link in my answer, because the links may break, and I found it completely informative and should read for any javascript developer.