手写js中的bind

2022-06-16 08:15:46 浏览数 (2)

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            // 手写实现 bind
            Function.prototype.bind =
                // Function.prototype.bind ||
                function (context) {
                    let args1 = Array.prototype.slice.call(arguments, 1);
                    let self = this;
                    return function () {
                        let args2 = Array.prototype.slice.call(arguments);
                        console.log([...args1, ...args2]);
                        return self.apply(context, [...args1, ...args2]);
                    };
                };
            var name = "xiaoming";
            let obj = {
                name: "xiaohong",
                getName: function () {
                    console.log(this.name);
                },
            };
            obj.getName(); // xiaohong

            let getName1 = obj.getName;
            getName1(); // xiaoming

            let getName2 = obj.getName.bind(obj);
            getName2(); // xiaohong

            let getName3 = obj.getName.bind(obj)(); // xiaohong

            let getName4 = obj.getName.bind(obj, 111)(); // [111] xiaohong

            let getName5 = obj.getName.bind(obj, 111, 222)(); // [111, 222] iaohong

            let getName6 = obj.getName.bind(obj, 111, 222)(333); // [111, 222, 333]  xiaohong

            obj.getName.call(obj); // xiaohong
        </script>
    </body>
</html>

0 人点赞