技术 · 思考 · 实践 · 成长

首页/JavaScript/正文

JavaScript 作用域、闭包与 this 指向

JavaScript1 次阅读

作用域、闭包、this 是 JS 的三座大山。本文一次讲透原理与规则,结尾附闭包计数器小案例。

一、作用域

let global = 1;                     // 全局作用域
function fn() {
    let local = 2;                  // 函数作用域
    if (true) {
        let block = 3;              // 块级作用域(let/const)
    }
    // console.log(block);          // ❌ ReferenceError
}

// 作用域链:内层可访问外层,外层不能访问内层
function outer() {
    let x = 1;
    function inner() {
        console.log(x);             // ✅ 沿作用域链向上找
    }
}

二、变量提升与暂时性死区

console.log(a);     // undefined(var 提升了声明)
var a = 1;

console.log(b);     // ❌ ReferenceError(let/const 暂时性死区)
let b = 2;

// 函数声明整体提升(可先调用后声明)
hello();
function hello() {}

三、闭包(重点)

闭包 = 函数 + 它能访问的外部作用域
即使外层函数已返回,内层函数仍持有外层变量的引用
function counter() {
    let count = 0;                  // 外层变量被内层函数"关住"
    return function () {
        return ++count;             // 外层返回后 count 依然存在
    };
}
const c1 = counter();
c1(); c1();        // 1, 2(独立计数)
const c2 = counter();
c2();              // 1(与 c1 互不影响)

闭包应用:数据私有(封装)、函数工厂、缓存、防抖节流的 timer 变量、柯里化。

四、this 指向(四大规则)

// 1. 普通函数调用:this = window(严格模式 undefined)
function f() { console.log(this); }
f();

// 2. 方法调用:this = 调用者
obj.method();          // this === obj

// 3. new 调用:this = 新建对象
new Person();          // this === 实例

// 4. 显式绑定:call/apply/bind
fn.call(obj, a, b);    // 立即执行,this = obj
fn.apply(obj, [a, b]);
const g = fn.bind(obj); // 返回新函数,永久绑定

// 箭头函数:没有自己的 this,继承定义时的外层
const obj2 = {
    name: 'Tom',
    hi: () => console.log(this.name),   // ❌ this 是外层(window)
    hello() { setTimeout(() => console.log(this.name), 0); }  // ✅ 箭头函数继承 hello 的 this
};

五、注意

  • 对象方法里用普通函数(this 才指向对象),回调用箭头函数(继承外层 this);
  • 事件处理函数里 this 是绑定元素(addEventListener);
  • 闭包会持有外层引用,长生命周期闭包注意内存泄漏;
  • bind 返回的函数不能再次 bind 改 this。

六、小案例:闭包计数器与缓存

// 1. 私有计数器(外部只能通过方法操作)
function createCounter(init = 0) {
    let count = init;                  // 私有变量
    return {
        inc: () => ++count,
        dec: () => --count,
        get: () => count,
    };
}
const c = createCounter(10);
c.inc(); c.inc(); c.dec();
console.log(c.get());       // 11
console.log(c.count);       // undefined(外部访问不到)

// 2. 记忆化(闭包缓存,递归加速)
function memoize(fn) {
    const cache = new Map();           // 闭包持有缓存
    return function (...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) return cache.get(key);
        const result = fn.apply(this, args);
        cache.set(key, result);
        return result;
    };
}

const slowFib = n => (n <= 1 ? n : slowFib(n - 1) + slowFib(n - 2));
const fib = memoize(slowFib);
console.log(fib(50));       // 瞬间出结果(缓存命中)

闭包两大经典:数据私有(计数器)与性能缓存(memoize) —— 面试和实战都常考。

七、总结

作用域链内层向外查找;let/const 有暂时性死区;闭包 = 函数+外部引用(私有化/缓存/防抖);this 四规则 + 箭头函数继承外层;对象方法用普通函数、回调用箭头。

梦想在远方闪烁,脚步则需踏实前行。

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读