Stanford CS142 笔记 - JavaScript
Functions
Arrow Functions and Traditional Functions
Traditional Functions
1 |
|
hoisting
JavaScript moves the function declarations to the top of their scope before execution.1
2
3
4console.log(add(2, 3)); // Works fine, even though add is defined later
function add(a, b) {
return a + b;
}“this” keyword
The value of “this” inside a traditional function depends on how the function is called.
Arrow Functions
1 |
|
No hoisting
“this” keyword
Arrow functions do not have their own “this” context. Instead, they inherit “this” from the surrounding scope where the arrow function is defined.
First Class Functions
- Functions are treated like variables in JavaScript
1 |
|
this
refers to the object that the method was called on. In this case, it refers to obj
.
- Functions can have properties
1 |
|
plus1.invocations
will be the number times function is called.
Closures
1 |
|
The
localFunc
returns theembedFunc
function.let myFunc = localFunc(10)
: This creates a new functionmyFunc
by calling localFunc with 10 as the argument.myFunc
now holds the reference to theembedFunc
closure, withlocalVar
initialized to 0 andargVar
set to 10.Each call
console.log(myFunc())
increases localVar by 1 and returns the updated sum.Closures are an advanced programming concept in JavaScript that allow functions to retain access to variables from their lexical scope even after the outer function has finished executing. The
embedFunc
closure retains access to localVar, argVar, and globalVar even afterlocalFunc
has finished executing.Using closures to encapsulate the state:
1 |
|
- The function is defined and immediately invoked, creating a new scope.
var myModule = (function () {do something})();
- myModule is not a function, but the return value of the function, which is an object.
- An IIFE (Immediately Invoked Function Expression) is a function that is executed right after it is defined.
myModule
is the return value of IIFE.
“this” keyword
In JavaScript, this
is a keyword that refers to an object. However, the exact object that this refers to depends on how a function is called.
- Global Context
1 |
|
In browsers, the global object is window
.
- Function Context
When a function is called as a method of an object, this refers to the object that the method is called on.
1 |
|
- Constructor Functions
1 |
|
this
inside Person
refers to the new object being created.
The new
Keyword creates a new object, sets this
to that object inside the constructor function, and returns the object.
Binding
1 |
|
The value of this
inside the function is not determined at the time the function is defined. Instead, it is determined at the time the function is called.
1 |
|
- We can explicitly set
this
:
1 |
|
.call()
: Calls a function with a giventhis
value..bind()
: Creates a new function that, when called, has itsthis
keyword set to the provided value.