Regular Function

function greet(name) {
  return "Hello, " + name;
}
console.log(greet("Alice"));

Arrow Function

const greet = name => `Hello, ${name}`;
const add = (a, b) => a + b;
console.log(greet("Bob"));

Closures

作用域和函数内部变量的持久化


The 'this' Keyword in JavaScript

The this keyword refers to the context in which a function is executed. The value of this is not determined by how a function is defined, but rather by how it's called.

Different Contexts for 'this'

  1. Global Context
console.log(this); // window (in browser)

  1. Function Context
function showThis() {
  console.log(this);
}

showThis(); // window (in browser, non-strict mode)

  1. Object Method Context
const user = {
  name: 'John',
  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
};

user.greet(); // "Hello, I'm John"

  1. Constructor Context
function User(name) {
  this.name = name;
}

const john = new User('John');
console.log(john.name); // "John"

  1. Event Handler Context