MST

星途 面试题库

面试题:JavaScript 中 bind 方法的特性及模拟实现

描述 JavaScript 中 bind 方法的特性,比如绑定后函数的 this 指向、参数传递等。并且请手动模拟实现一个类似 bind 功能的函数。
49.4万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

JavaScript 中 bind 方法的特性

  1. this 指向bind 方法会创建一个新函数,这个新函数的 this 会被绑定到 bind 方法的第一个参数上。即使新函数在其他地方被调用,其 this 始终指向绑定的值。
  2. 参数传递bind 方法除了第一个参数用于绑定 this 外,后续传入的参数会作为新函数的预设参数,在新函数调用时,会将这些预设参数与新函数实际传入的参数按照顺序合并,作为新函数的最终参数。

手动模拟实现类似 bind 功能的函数

Function.prototype.myBind = function (context) {
    if (typeof this!== 'function') {
        throw new TypeError('this must be a function');
    }
    const self = this;
    const args = Array.prototype.slice.call(arguments, 1);
    return function () {
        const innerArgs = Array.prototype.slice.call(arguments);
        const finalArgs = args.concat(innerArgs);
        return self.apply(context, finalArgs);
    };
};