1. What are the two predominant models for how Scope works used by the majority of programming languages?
lexical scope
dynamic scope
lexical scope
var result = (function (a) {
function foo(b) {
return bar(5);
function bar(c) {
return a + b + c;
}
}
return foo(2);
})(3);
console.log(result);
There are 4
Scopes
:global scope
- anonymous function (iife) scope
-- foo scope
--- bar scope
Output:
10
when an identifier of an inner scope
shadows
an identifier of an outer scope.
NOTE: replace window
with global
if you are using node.js
var name = "John";
function foo(name) {
function bar() {
var name = "Doe";
return (function baz() {
return name;
})();
}
return bar();
}
console.log(foo(name));
"Doe"
var a = 2;
console.log(window.a);
2
function foo() {
var a = 3;
}
console.log(foo.a);
undefined
function foo() {
// noop
}
foo.a = 4;
console.log(foo.a);
4
var a = 5;
function foo() {
a = 10;
console.log(a);
console.log(window.a);
}
foo();
10
10
"use strict";
function foo(str) {
eval(str);
console.log(z);
}
foo("var z = 4;");
ReferenceError: z is not defined
function foo(str) {
eval(str);
console.log(x);
}
foo("var x = 5;");
5
function foo(str) {
eval(str);
}
foo("y = 7;");
console.log(y);
7
function foo(str) {
eval(str);
}
foo("var y = 7;");
console.log(y);
ReferenceError: y is not defined
function foo(o) {
with (o) {
a = 5;
}
}
var obj = { a: 2 };
foo(obj);
console.log(obj.a);
5
function foo(o) {
with (o) {
b = 10;
}
}
var obj = { a: 2 };
foo(obj);
console.log(obj.b);
undefined
function foo(o) {
with (o) {
b = 5;
}
}
var obj = { a: 2 };
foo(obj);
console.log(b);
5
function foo(o) {
with (o) {
b = 5;
}
}
var obj = { a: 2 };
foo(obj);
console.log(a);
ReferenceError: a is not defined
function foo(o) {
with (o) {
var b = 3;
}
console.log(b);
}
var obj = { b: 2 };
foo(obj);
undefined
function foo(o) {
with (o) {
var b;
}
b = 3;
console.log(b);
}
var obj = { b: 2 };
foo(obj);
3
function foo(o) {
with (o) {
var b = 3;
}
}
var obj = { b: 2 };
foo(obj);
console.log(b);
ReferenceError: b is not defined
function foo(o) {
with (o) {
b = 3;
}
}
var obj = { b: 2 };
foo(obj);
console.log(b);
ReferenceError: b is not defined
"use strict";
function foo(o) {
with (o) {
b = 3;
}
}
var obj = { a: 2 };
foo(obj);
console.log(b);
SyntaxError: Strict mode code may not include a with statement
code will run slower no matter how smart the Engine is, because these mechanisms defeat the Engine's ability to perform compile-time optimizations.
none. both are the same, actually is more proper to call it
Lexical Scope