【JS】手写实现call、apply

目录

1、call、apply作用、区别

2、实际开发中call、apply的应用场景

3、手写_call函数

4、手写_bind函数


1、call、apply作用、区别

作用:改变this指向。

区别:参数的区别。call传数据,apply传数组

2、实际开发中call、apply的应用场景

  • js的继承:1)原型链继承;2)构造函数继承-call实现;
  • js的数据类型-Object.prototype.toString.call();
  • es5把伪数组转化成数组-Array.prototype.slice.call(arguments);

3、手写_call函数

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8>
    </head>
    <body>
                 <script type="text/javascript">
            // 补全代码
            Function.prototype._call = function(obj) {
                // 1.判断调用对象是否是函数
                if (typeof this !== 'function') console.error('type error')
                // 2.获取参数
                let args = [...arguments].slice(1), res = null
                // 3、判断上下文是否存在,不存在设置为window
                obj = obj || window
                // 4、将调用函数设置为对象的方法
                obj.fn = this
                // 5、调用方法
                res = obj.fn(...args)
                // 6、移除属性
                //delete obj.fn
                return res
            }
            
        </script>
    </body>
</html>

4、手写_bind函数

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8>
    </head>
    <body>
    	
        <script type="text/javascript">
             Function.prototype._apply = function(obj) {
            // 1.判断调用对象是否是函数
                if (typeof this !== 'function') console.error('type error')
                // 2.获取参数
                let args = arguments[1], res = null
                // 3、判断上下文是否存在,不存在设置为window
                obj = obj || window
                // 4、将调用函数设置为对象的方法
                obj.fn = this
                // 5、调用方法
                if(args){
                    res = obj.fn(...args)
                }else{
                    res = obj.fn()
                }
                //6、移除属性
                delete obj.fn
                return res
             }
            
        </script>
    </body>
</html>


版权声明:本文为m0_57946086原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。