JS 面试题常见知识点(三)—— 闭包

  1. 函数作为返回值

    function create() {
        const a = 100;
        return function () {
            consolo.log(a);
        }
    }
    const fn = create();
    const a = 200;
    fn() // 100
    
  2. 函数作为参数被传递

    function print(fn) {
        const a = 200;
        fn();
    }
    const a = 100;
    function fn() {
        consolo.log(a);
    }
    
    // 自由变量的查找,是在函数定义的地方,向上级作用域查找
    // 不是在执行的地方
    
  3. this的不同场景,如何取值

    • 当做普通函数被调用时,this取window。
    • 使用call、apply、bind,this是传入的值。
    • 做为对象方法调用,this就是对象方法本身。
    • 在class的方法中调用,this是实例本身。
    • 在箭头函数中,this是上一级this作用域的值。
  4. 手写bind

    Function.prototype.bind1 = function () {
        // 将参数拆解为数组
        // const args = Array.prototype.slice.call(arguments);
        const args = [...arguments];
        // 获取 this (数组的第一项)
        const t = args.shift();
        // 返回一个函数
        return () => {
            return this.apply(t, args);
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值