JavaScript 核心概念
原型链
JavaScript 通过原型链实现对象继承。
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
const alice = new Person('Alice');
alice.sayHello();
// 原型链:alice → Person.prototype → Object.prototype → null
闭包
函数可以访问其外部作用域中的变量。
function createCounter() {
let count = 0;
return {
increment: () => ++count,
get: () => count
};
}
const counter = createCounter();
counter.increment(); // 1
counter.get(); // 1
// count 无法从外部直接访问 — 实现了私有变量
Promise
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: 'Alice' });
else reject(new Error('Invalid ID'));
}, 1000);
});
}
fetchUser(1)
.then(user => console.log(user))
.catch(err => console.error(err));
async/await
async function getUser(id) {
try {
const user = await fetchUser(id);
return user;
} catch (err) {
console.error(err);
return null;
}
}
this 绑定
const obj = {
name: 'Alice',
greet() { console.log(this.name); }
};
obj.greet(); // 'Alice'
const greet = obj.greet;
greet(); // undefined — 丢失上下文
const bound = obj.greet.bind(obj);
bound(); // 'Alice' — 显式绑定
事件循环
console.log('1'); // 同步
setTimeout(() => console.log('2'), 0); // 宏任务
Promise.resolve().then(() => console.log('3')); // 微任务
console.log('4'); // 同步
// 输出:1 → 4 → 3 → 2
执行顺序:同步代码 → 微任务队列(Promise.then)→ 宏任务队列(setTimeout)