首页 > 技术文章 > js基础知识02【前端面试】

formattor 2021-03-17 15:52 原文

作用域

闭包

作为参数被传入以及作为返回值返回

自由变量的查找,是在函数定义的地方,向上级作用域查找,而不是在执行的地方。

this

取值是在执行时确认,而不是定义

应用场景:

  1.普通函数调用

  2.call apply bind

    call()、apply()、bind() 都是用来重定义 this 这个对象的

    区别:

      1.call的参数后边挨着放。call(obj,params1,params2)

      2.apply的参数第二个在数组中。call(obj,['params1','params2'])

      3.bind的参数同第一个但是后边得加()到新的函数。call(obj,params1,params2)()

               JavaScript 中 call()、apply()、bind() 的用法

  3.对象方法调用

  4.class的方法中调用

  5.箭头函数(指向上一级的this)

问题

this在不同场景下如何取值

手写bind函数

// 模拟 bind
Function.prototype.bind1 = function () {
    // 将参数拆解为数组
    const args = Array.prototype.slice.call(arguments)

    // 获取 this(数组第一项)
    const t = args.shift()

    // fn1.bind(...) 中的 fn1
    const self = this

    // 返回一个函数
    return function () {
        return self.apply(t, args)
    }
}

闭包应用场景

  1.隐藏数据,只提供API。比如一个类的数据不能被外界修改

作用域和自由变量

闭包

this

推荐阅读