26. var a = 2;
foo(); // works because `foo()`
// declaration is "hoisted"
function foo() {
a = 3;
console.log( a ); // 3
var a; // declaration is "hoisted"
// to the top of `foo()`
}
console.log( a ); // 2
27. var a = "42";
var b = Number( a ); // explicitly coerced here
a; // "42"
b; // 42 -- the number!
var a = "42";
var b = a * 1; // "42" implicitly coerced to 42 here
a; // "42"
b; // 42 -- the number!
28. var a = "abc";
a.length; // 3
a.toUpperCase(); // "ABC"
var a = new String( "abc" ); // Manually boxing
var b = new Number( 42 );
var c = new Boolean( true );
a.valueOf(); // "abc"
b.valueOf(); // 42
c.valueOf(); // true
b = a + ""; // ‘b’ has the unboxed primitive value "abc"
typeof a; // "object"
typeof b; // "string"
29. Just a few more things
• Function
• Scope
• Closure
30. function foo() {
return 42;
}
foo.bar = "hello world";
typeof foo; // "function"
typeof foo(); // "number"
typeof foo.bar; // "string“
function foo(a) {
console.log( a + b );
}
var b = 2;
foo( 2 ); // 4
31. function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
Notas del editor
1
Married with Children is close to the end
1 year since the death of Kurt Cobain
Greenday became mainstream in 1995 with the song “Basket Case” (from record “Dookie”)
National Center for Supercomputing Applications (NCSA)
Brendan Eich
National Center for Supercomputing Applications (NCSA)
[string, number, Boolean, null, undefined, object, symbol (ES6)]
typed values not typed variables – variables are just containers
Object -> compound value -> properties -> accessed using the dot notation or backet notation (object[“foo bar”])
Other value types (commonly used) -> Array, Function -> specialized version of object type
typeof null is an interesting case (returning “object” )
Declarations “moved” to the top of its enclosing scope -> due to the way the code is compiled
hoisted function declarations (accepted)
vars & functions declarations
coercion comes in two forms -> explicit & implicit
is not evil, nor does it have to be surprising
Natives -> object wrappers -> subtypes of object
Giving primitives props and methods
Better let the boxing happen implicitly
Functions -> Subtypes of objects -> First Class Citizens –> Have own scope ->arguments stored as “array”
Scope -> well-defined set of rules for storing variables & for finding those variables at a later time
current context of execution -> values and expressions are "visible”
child scopes have access to parent scopes, but not vice-versa
special kind of object -> combines function and it’s environment (any local vars that were scope when function created)
reach nested function from outer scope
“remembers” the environment in which it was created
emulating private methods