2

参考

https://www.cnblogs.com/moqiu...

作用

  1. call和apply用来调用函数,并用指定对象(第一个参数)替换函数的 this 值,同时用指定数组替换函数的参数
  2. 我自己不用声明一个构造函数,就借用现成的构造函数,从而精简代码

call

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        var obj = {
            value: '1'
        }

        function fn(name, age) {
            this.name = name;
            this.age = age;
            this.say = function() {
                alert(this.name + this.age)
            }
        }
    </script>
    <!-- call -->
    <script>
        Function.prototype.call2 = function(context){
            var context = context || window;
            context.fn = this;
            var args = [];
            var result;
            for(var i =1;i<arguments.length;i++){
                args.push(`arguments[${i}]`)
            }
            result = eval(`context.fn(${args})`)
            delete context.fn;
            return result;
        }
        fn.call(obj, 'jie', 10)
        obj.say()
        fn.call2(obj, 'biao', 20)
        obj.say()
    </script>
</body>

</html>

apply

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        var obj = {
            value: '1'
        }

        function fn(name, age) {
            this.name = name;
            this.age = age;
            this.say = function() {
                alert(this.name + this.age)
            }
        }
    </script>
    <script>
        Function.prototype.apply2 = function(context,arr){
            var context = Object(context) || window;
            context.fn = this;
            var args = [];
            var result;
            if(!arr){
                result = context.fn()
            }else{
                for(var i=0;i<arr.length;i++){
                    args.push(`arr[${i}]`)
                }
                result = eval(`context.fn(${args})`)
            }
            delete context.fn;
            return result;
        }
        fn.apply(obj, ['jie', 10])
        obj.say()
        fn.apply2(obj, ['biao', 20])
        obj.say()
    </script>
</body>

</html>

效果

clipboard.png


渣渣辉
1.3k 声望147 粉丝