urlname
type
password
SyncToConfluence
SyncToConfluence
category
date
slug
icon
Button
catalog
summary
tags
cover
Status
BusyTime
Status 1
status
主要记录关于JavaScript学习过程中的基础知识,用于复习和总结,主要内容借助GPT生成。
📝 涉及内容
- 变量、常量
- 数据类型
- 流程控制
- 函数
- 对象定义、属性、方法、构造函数
- 类、继承
- 原型链
- 高阶函数
- 作用域与闭包
- 错误处理
- 类型转换
- 事件循环和异步编程
🆎 数据类型
原始类型
number
:数值类型,例如整数、浮点数
string
:字符串
boolean
:布尔值(true
或false
)
null
:空值
undefined
:未定义
Symbol
:独特的标识符(ES6 引入)
BigInt
:大整数
引用类型
Object
:对象
Array
:数组
Function
:函数
Date
:日期
let num = 42; // number let str = "Hello, world!"; // string let bool = true; // boolean let n = null; // null let u; // undefined let sym = Symbol("unique"); // Symbol let bigInt = 1234567890123456789012345678901234567890n; // BigInt let obj = { name: "Alice", age: 25 }; // Object let arr = [1, 2, 3, 4]; // Array let func = function() { return "I am a function"; }; // Function let date = new Date(); // Date console.log(num, str, bool, n, u, sym, bigInt, obj, arr, func(), date);
变量声明
三种不同的声明变量方式:
var
:有函数作用域和可提升性(hoisting)
let
:有块作用域
const
:定义常量,有块作用域,且不可重新赋值
var globalVar = "I'm global"; let blockVar = "I'm block-scoped"; const constantValue = 100; if (true) { var globalVar2 = "Still global"; let blockVar2 = "Block-scoped"; const constantValue2 = "Constant"; } console.log(globalVar); // 可访问 console.log(globalVar2); // 可访问 // console.log(blockVar2); // 报错:blockVar2 未定义 // console.log(constantValue2); // 报错:constantValue2 未定义
流程控制语句
- 条件语句:
if-else
、switch
- 循环语句:
for
、while
、do-while
、for-in
、for-of
// if-else let age = 20; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are a minor."); } // switch let fruit = "apple"; switch (fruit) { case "apple": console.log("Apple selected"); break; case "orange": console.log("Orange selected"); break; default: console.log("Unknown fruit"); break; } // for for (let i = 0; i < 5; i++) { console.log(`for loop count: ${i}`); } // while let count = 3; while (count > 0) { console.log(`Countdown: ${count}`); count--; } // do-while let n = 0; do { console.log(`do-while loop count: ${n}`); n++; } while (n < 3); // for-in let person = { name: "John", age: 30 }; for (let key in person) { console.log(`${key}: ${person[key]}`); } // for-of let fruits = ["apple", "banana", "grape"]; for (let fruit of fruits) { console.log(fruit); }
函数
JavaScript
中的函数有多种定义方式:普通函数、匿名函数、箭头函数,以及具名或匿名的回调函数。// 普通函数 function greet(name) { return `Hello, ${name}!`; } console.log(greet("Alice")); // 匿名函数 const square = function(x) { return x * x; }; console.log(square(4)); // 箭头函数 const multiply = (a, b) => a * b; console.log(multiply(2, 3)); // 回调函数 function calculate(a, b, operation) { return operation(a, b); } const add = (x, y) => x + y; const subtract = (x, y) => x - y; console.log(calculate(10, 5, add)); // 使用回调函数加法 console.log(calculate(10, 5, subtract)); // 使用回调函数减法
对象相关
定义与使用
- 对象是属性和方法的集合,可以通过对象字面量、构造函数或
Object.create
创建。
// 使用对象字面量 const person = { name: "Alice", age: 30, greet() { return `Hello, my name is ${this.name}.`; } }; console.log(person.name); // 输出:Alice console.log(person.greet()); // 输出:Hello, my name is Alice. // 使用构造函数 function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const myCar = new Car("Toyota", "Corolla", 2021); console.log(myCar.make); // 输出:Toyota // 使用 Object.create const prototype = { greet() { return "Greetings!"; } }; const obj = Object.create(prototype); obj.name = "NewObject"; console.log(obj.name); // 输出:NewObject console.log(obj.greet()); // 输出:Greetings!
构造函数
- 构造函数用于创建和初始化对象。
- 通过
new
关键字实例化时,构造函数的this
指向新对象。
function Dog(name, breed) { this.name = name; this.breed = breed; this.bark = function() { return `${this.name} says Woof!`; }; } const myDog = new Dog("Buddy", "Golden Retriever"); console.log(myDog.name); // 输出:Buddy console.log(myDog.bark()); // 输出:Buddy says Woof!
属性与方法
- 对象的属性可以是数据属性或访问器属性。
- 方法通常是函数,绑定到对象的属性中。
// 数据属性和方法 const book = { title: "JavaScript: The Good Parts", author: "Douglas Crockford", pages: 176, getInfo() { return `${this.title} by ${this.author}`; } }; console.log(book.title); // 输出:JavaScript: The Good Parts console.log(book.getInfo()); // 输出:JavaScript: The Good Parts by Douglas Crockford // 访问器属性 const user = { _firstName: "John", _lastName: "Doe", get fullName() { return `${this._firstName} ${this._lastName}`; }, set fullName(name) { const parts = name.split(" "); this._firstName = parts[0]; this._lastName = parts[1]; } }; console.log(user.fullName); // 输出:John Doe user.fullName = "Jane Smith"; console.log(user.fullName); // 输出:Jane Smith
类与继承
- 在 ES6 中引入了
class
语法,使得面向对象编程更加清晰易懂。
class
支持继承、静态方法、以及构造器等。
// 基类 class Animal { constructor(name) { this.name = name; } sound() { return `${this.name} makes a sound.`; } } // 派生类 class Cat extends Animal { constructor(name, color) { super(name); // 调用父类构造函数 this.color = color; } sound() { return `${this.name} says Meow!`; } } const myCat = new Cat("Whiskers", "white"); console.log(myCat.name); // 输出:Whiskers console.log(myCat.color); // 输出:white console.log(myCat.sound()); // 输出:Whiskers says Meow!
原型链
- JavaScript 使用原型继承机制。
- 对象的原型链是一系列对象的链表,使对象能继承并操作其原型链上的属性和方法。
// 构造函数 function Bird(name) { this.name = name; } // 给 Bird 的原型添加方法 Bird.prototype.fly = function() { return `${this.name} is flying.`; }; // 创建 Bird 实例 const sparrow = new Bird("Sparrow"); console.log(sparrow.fly()); // 输出:Sparrow is flying. // 验证原型链 console.log(sparrow.__proto__ === Bird.prototype); // 输出:true console.log(Bird.prototype.__proto__ === Object.prototype); // 输出:true console.log(Object.prototype.__proto__); // 输出:null
注意事项
- 使用构造函数时,确保使用
new
关键字来创建实例,否则this
指向全局对象。
- 类的静态方法不能通过实例调用,而是通过类本身调用。
- 原型链中属性查找是从下往上查找,找到就停止搜索,找不到则返回
undefined
。
- 不要直接修改内置对象的原型,这样做可能破坏全局环境。
作用域与闭包
- 作用域:
- JavaScript 中有全局作用域、函数作用域和块作用域。
- 块作用域由
let
和const
引入,使得在块(如循环或条件语句)中的变量仅在块内可见。
- 闭包:
- 闭包是函数与其词法环境的组合,使函数可以访问函数外部的变量,即使该函数在外部执行。
- 闭包常用于数据隐藏和工厂函数。
// 全局作用域 let globalVar = "I'm a global variable"; function functionScope() { // 函数作用域 let functionVar = "I'm a function scope variable"; console.log(globalVar); // 输出:I'm a global variable console.log(functionVar); // 输出:I'm a function scope variable } functionScope(); // console.log(functionVar); // 会报错,因为 functionVar 在函数作用域外不可见 // 块作用域 if (true) { let blockVar = "I'm a block scope variable"; console.log(blockVar); // 输出:I'm a block scope variable } // console.log(blockVar); // 会报错,因为 blockVar 在块作用域外不可见 // 闭包 function counter() { let count = 0; return function() { count++; return count; }; } const increment = counter(); console.log(increment()); // 输出:1 console.log(increment()); // 输出:2 console.log(increment()); // 输出:3
事件循环和异步编程
- 事件循环:
- 解释 JavaScript 如何异步处理事件和执行任务。
- 它使代码在执行时保持非阻塞状态。
- 异步编程:
- 通过回调、
Promise
和async/await
处理异步操作,如定时器和网络请求。
// 异步编程示例 console.log("Start"); setTimeout(() => { console.log("Timeout callback"); }, 1000); console.log("End"); // 预期输出: // Start // End // Timeout callback // Promise 示例 const fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => resolve("Data received"), 2000); }); }; fetchData().then(data => console.log(data)); // 输出:Data received // async/await 示例 async function getData() { const data = await fetchData(); console.log(`Async/await: ${data}`); } getData(); // 输出:Async/await: Data received
错误处理
- JavaScript 使用
try-catch
捕获并处理异常。自定义错误类可用于生成特定的错误信息。
// try-catch 结构 try { let num = 10; if (num > 5) { throw new Error("Number is too high!"); } } catch (e) { console.log(`Caught error: ${e.message}`); // 输出:Caught error: Number is too high! } finally { console.log("This always runs."); // 输出:This always runs. } // 自定义错误类 class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } function validateAge(age) { if (age < 0) { throw new ValidationError("Age cannot be negative!"); } return `Age is valid: ${age}`; } try { console.log(validateAge(-3)); } catch (e) { console.log(`Validation error: ${e.message}`); // 输出:Validation error: Age cannot be negative! }
类型转换
- 显式转换:使用
Number
、String
、Boolean
等转换方法。
- 隐式转换:通过自动类型转换操作符。
// 显式类型转换 let numStr = "123"; let num = Number(numStr); console.log(typeof num); // 输出:number let bool = Boolean(1); console.log(bool); // 输出:true // 隐式类型转换 console.log("5" + 5); // 输出:55,字符串连接 console.log("5" - 2); // 输出:3,隐式转换为数字
严格模式
- 使代码执行更严格的检查,以避免潜在的错误。
- 启动方式:
use strict;
"use strict"; try { undeclaredVariable = 10; // 报错:undeclaredVariable 未定义 } catch (e) { console.log(e.message); // 输出:undeclaredVariable is not defined } function testStrictMode() { "use strict"; // 在严格模式下无法删除变量 let x = 3.14; // delete x; // 报错:Cannot delete variable 'x' }
高阶函数
- 高阶函数是可以接受函数作为参数,或返回另一个函数的函数。
- 常用的数组高阶函数包括
map
、filter
和reduce
。
// 使用 map 函数 let numbers = [1, 2, 3, 4]; let squares = numbers.map(num => num * num); console.log(squares); // 输出:(4) [1, 4, 9, 16] // 使用 filter 函数 let evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // 输出:(2) [2, 4] // 使用 reduce 函数 let sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // 输出:10
- 作者:CoderWdd
- 链接:https://www.wuinsights.top/article/01HXPH27FRNHV8PN3RNSWTV1N7
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章