JavaScript常问面试题(持续更新中)

欢迎来到我的世界 / 2023-07-22 / 原文

this,作用域,闭包

1. 谈谈对 this 指向问题的理解

  • JS中this的指向非常灵活,会根据函数的调用方式和所处环境不同而发生变化

  • this关键字用来指代当前执行环境的上下文

  • this永远指向一个对象

  • this的指向取决于函数调用的位置,或通过call,apply,bind修改

  • this指向跟调用有关,跟定义无关

2. 手写实现 call、apply、bind 函数(apply只是传入参数为数组)

//手写实现call
Function.prototype.selfCall = function( context, ...params ) {
    context == null ? context = window : null
    !/^(object|function)$/.test( typeof context ) ? context = Object(context) : null
    //定义唯一的key
    let _this = this, result = null, UNIQUE_KEY = Symbol('UNIQUE_KEY')
    context[UNIQUE_KEY] = _this
    result = context[UNIQUE_KEY](...params)
    delete context[UNIQUE_KEY]
    return result
}
//手写实现bind
Function.prototype.selfBind = function( context, ...outParams ) {
    let _this = this
    return function(...innerParams) {
        _this.selfCall( context, ...outParams.concat(...innerParams ))
    }
}