Stanford CS142 笔记 - JavaScript
Functions
Arrow Functions and Traditional Functions
Traditional Functions
function add(a, b) {
return a + b;
}- hoisting
JavaScript moves the function declarations to the top of their scope before execution.
console.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
const add = (a, b) => {
return a + b;
};- 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
let obj = {count: 0};
obj.increment = function (amount) {
this.count += amount;
return this.count;
}
obj.increment(1); // returns 1
obj.increment(3); // returns 4this refers to the object that the method was called on. In this case, it refers to obj.
- Functions can have properties
function plus1(value) {
if (plus1.invocations == undefined) {
plus1.invocations = 0;
}
plus1.invocations++;
return value + 1;
}plus1.invocations will be the number times function is called.
Closures
let globalVar = 1;
function localFunc(argVar) {
let localVar = 0;
function embedFunc() {return ++localVar + argVar + globalVar;}
return embedFunc;
}
let myFunc = localFunc(10);- The
localFuncreturns theembedFuncfunction. let myFunc = localFunc(10): This creates a new functionmyFuncby calling localFunc with 10 as the argument.myFuncnow holds the reference to theembedFuncclosure, withlocalVarinitialized to 0 andargVarset 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
embedFuncclosure retains access to localVar, argVar, and globalVar even afterlocalFunchas finished executing. - Using closures to encapsulate the state:
var myModule = (function () {
// Private variables and functions
var privateVariable = 'I am private';
function privateFunction() {
console.log(privateVariable);
}
// Public API
return {
publicMethod: function () {
privateFunction();
},
publicProperty: 'I am public'
};
})();
myModule.publicMethod();- 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.
myModuleis 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
// outside of any function
console.log(this); // In a browser, this will log the window objectIn 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.
const obj = {
value: 42,
getValue: function() {
return this.value;
}
};
console.log(obj.getValue()); // 42- Constructor Functions
function Person(name) {
this.name = name;
}
const person = new Person('Alice');
console.log(person.name); // Alicethis 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
function greet() {
console.log('Hello, ' + this.name);
}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.
const person = {
name: 'Alice',
greet: greet
};
person.greet(); // `this` refers to `person`, so it logs `Hello, Alice`- We can explicitly set
this:
function greet() {
console.log('Hello, ' + this.name);
}
const person = { name: 'Alice' };
greet.call(person); // Hello, Alice
const greetPerson = greet.bind(person);
greetPerson(); // Hello, Alice.call(): Calls a function with a giventhisvalue..bind(): Creates a new function that, when called, has itsthiskeyword set to the provided value.