Professional JavaScript for Web Developers 第四版學習筆記 CHAPTER 4: VARIABLES, SCOPE, AND MEMORY
目錄
Primitive and Reference Values 101
Dynamic Properties 102
Copying Values 103
Argument Passing 103
Determining Type 105
Execution Context and Scope 106
Scope Chain Augmentation 108
Variable Declaration 109
Function Scope Declaration Using var 109
Block Scope Declaration Using let 111
Constant Declaration Using const 112
Identifier Lookup 113
Garbage Collection 114
Mark-and-Sweep 115
Reference Counting 115
Performance 116
Managing Memory 117
Performance Boosts with const and let Declarations 118
Hidden Classes and the delete Operation 118
Memory Leaks 119
Static Allocation and Object Pools 120
Summary 122
reference value
let obj1 = new Object();
let obj2 = obj1;
obj1.name = "Nicholas";
console.log(obj2.name); // "Nicholas"
The difference is that this value is actually a pointer to an object stored on the heap. Once the operation is complete, two variables point to exactly the same object, so changes to one are reflected on the other.往函數中傳遞參數也是一樣。
-------------------------------------------------
The concept of execution context, referred to as context for simplicity, is of the utmost importance in JavaScript. The execution context of a variable or function defines what other data it has access to, as well as how it should behave. Each execution context has an associated variable object upon which all of its defined variables and functions exist. This object is not accessible by code but is used behind the scenes to handle data.
-------------------------------------------------
When code is executed in a context, a scope chain of variable objects is created. The purpose of the scope chain is to provide ordered access to all variables and functions that an execution context has access to. The front of the scope chain is always the variable object of the context whose code is executing. If the context is a function, then the activation object is used as the variable object. An activation object starts with a single defined variable called arguments. (This doesn’t exist for the global context.) The next variable object in the chain is from the containing context, and the next after that is from the next containing context. This pattern continues until the global context is reached; the global context’s variable object is always the last of the scope chain.
-------------------------------------------------
The const declaration only applies to the top-level primitive or object. In other words, a const variable assigned to an object cannot be reassigned to another reference value, but the keys inside that object are not protected.
const o1 = {};
o1 = {}; // TypeError: Assignment to a constant variable;
const o2 = {};
o2.name = 'Jake';
console.log(o2.name); // 'Jake'