JS手写-this绑定实现

在 JavaScript 中,bindcallapply 方法都可以用来改变函数的 this 指向。下面我们将分别实现这些方法的简单版本。

1. 实现 bind

bind 方法创建一个新的函数,在调用时设置 this 值,并返回这个新的函数。

javascript 复制代码
Function.prototype.myBind = function (context) {
    if (typeof this !== 'function') {
        throw new TypeError('Not a function');
    }

    const fn = this;
    const args = Array.prototype.slice.call(arguments, 1);

    return function bound() {
        const boundArgs = Array.prototype.slice.call(arguments);
        return fn.apply(context, args.concat(boundArgs));
    };
};

2. 实现 call

call 方法立即调用函数,并设置 this 值,同时传递参数列表。

javascript 复制代码
Function.prototype.myCall = function (context) {
    if (typeof this !== 'function') {
        throw new TypeError('Not a function');
    }

    context = context || window;
    const args = Array.prototype.slice.call(arguments, 1);

    context.fn = this;
    const result = context.fn(...args);
    delete context.fn;

    return result;
};

3. 实现 apply

apply 方法与 call 类似,但传递的参数是一个数组。

javascript 复制代码
Function.prototype.myApply = function (context, args) {
    if (typeof this !== 'function') {
        throw new TypeError('Not a function');
    }

    context = context || window;
    args = args || [];

    context.fn = this;
    const result = context.fn(...args);
    delete context.fn;

    return result;
};

示例代码

下面是一个完整的示例,展示了如何使用这些自定义的方法:

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自定义 bind, call, apply</title>
</head>
<body>
    <script type="text/javascript">
        Function.prototype.myBind = function (context) {
            if (typeof this !== 'function') {
                throw new TypeError('Not a function');
            }

            const fn = this;
            const args = Array.prototype.slice.call(arguments, 1);

            return function bound() {
                const boundArgs = Array.prototype.slice.call(arguments);
                return fn.apply(context, args.concat(boundArgs));
            };
        };

        Function.prototype.myCall = function (context) {
            if (typeof this !== 'function') {
                throw new TypeError('Not a function');
            }

            context = context || window;
            const args = Array.prototype.slice.call(arguments, 1);

            context.fn = this;
            const result = context.fn(...args);
            delete context.fn;

            return result;
        };

        Function.prototype.myApply = function (context, args) {
            if (typeof this !== 'function') {
                throw new TypeError('Not a function');
            }

            context = context || window;
            args = args || [];

            context.fn = this;
            const result = context.fn(...args);
            delete context.fn;

            return result;
        };

        // 测试对象
        const obj = {
            name: '牛客网'
        };

        // 测试函数
        function greet(message) {
            console.log(`${message}, ${this.name}`);
        }

        // 使用 myBind
        const greetBound = greet.myBind(obj, '欢迎来到');
        greetBound(); // 输出: 欢迎来到, 牛客网

        // 使用 myCall
        greet.myCall(obj, '欢迎来到'); // 输出: 欢迎来到, 牛客网

        // 使用 myApply
        greet.myApply(obj, ['欢迎来到']); // 输出: 欢迎来到, 牛客网
    </script>
</body>
</html>

详细步骤

  1. 实现 myBind

    • 检查调用者是否为函数。
    • 获取上下文 context 和传入的参数 args
    • 返回一个新的函数 bound,在调用时使用 apply 方法设置 this 值并传递参数。
  2. 实现 myCall

    • 检查调用者是否为函数。
    • 获取上下文 context 和传入的参数 args
    • 将函数赋值给 context 的一个临时属性 fn,调用该属性并传递参数,然后删除该属性。
  3. 实现 myApply

    • 检查调用者是否为函数。
    • 获取上下文 context 和传入的参数数组 args
    • 将函数赋值给 context 的一个临时属性 fn,调用该属性并传递参数,然后删除该属性。

测试

  1. 使用 myBind

    • 创建一个绑定了 obj 上下文的新函数 greetBound,并调用它。
  2. 使用 myCall

    • 直接调用 greet 函数,并设置 objthis 值。
  3. 使用 myApply

    • 直接调用 greet 函数,并设置 objthis 值,参数以数组形式传递。
相关推荐
weixin_472339463 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击4 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue5 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
m0_555762906 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
像风一样自由20206 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
浪裡遊7 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
lzb_kkk7 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼8 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
简佐义的博客8 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
Liudef068 小时前
2048小游戏实现
javascript·css·css3