Stanford CS142 笔记 - JavaScript

Functions

Arrow Functions and Traditional Functions

Traditional Functions

1
2
3
function add(a, b) {
return a + b;
}
  • hoisting
    JavaScript moves the function declarations to the top of their scope before execution.

    1
    2
    3
    4
    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

1
2
3
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
1
2
3
4
5
6
7
let obj = {count: 0}; 
obj.increment = function (amount) {
this.count += amount;
return this.count;
}
obj.increment(1); // returns 1
obj.increment(3); // returns 4

this refers to the object that the method was called on. In this case, it refers to obj.

  • Functions can have properties
1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
let globalVar = 1; 
function localFunc(argVar) {
let localVar = 0;
function embedFunc() {return ++localVar + argVar + globalVar;}
return embedFunc;
}
let myFunc = localFunc(10);
  • The localFunc returns the embedFunc function.

  • let myFunc = localFunc(10): This creates a new function myFunc by calling localFunc with 10 as the argument. myFunc now holds the reference to the embedFunc closure, with localVar initialized to 0 and argVar 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 after localFunc has finished executing.

  • Using closures to encapsulate the state:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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. 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
2
// outside of any function
console.log(this); // In a browser, this will log the window object

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
2
3
4
5
6
7
8
const obj = {
value: 42,
getValue: function() {
return this.value;
}
};

console.log(obj.getValue()); // 42
  • Constructor Functions
1
2
3
4
5
6
function Person(name) {
this.name = name;
}

const person = new Person('Alice');
console.log(person.name); // Alice

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
2
3
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.

1
2
3
4
5
const person = {
name: 'Alice',
greet: greet
};
person.greet(); // `this` refers to `person`, so it logs `Hello, Alice`
  • We can explicitly set this:
1
2
3
4
5
6
7
8
9
10
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 given this value.
  • .bind(): Creates a new function that, when called, has its this keyword set to the provided value.

Stanford CS142 笔记 - JavaScript
https://thiefcat.github.io/2024/08/02/CS142/JavaScript/
Author
小贼猫
Posted on
August 2, 2024
Licensed under