js的apply和call

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //第一个用途:函数上下文模式改变this的指向
        var age=19;
        function fun() {
            console.log(this.age);
        }

        var obj={
            age:26
        };
        fun.apply(obj);
        fun.call(obj)
        //总结:apply和call,第一个参数功能都是一样,都是可以改变this指向为第一个参数对象。
        //当传递对象为null的时候,为window调用

        //应用1:将参数用“-”拼接
        function fun2() {
            //arguments是一个伪装数组,不能调用join方法,通过apply转换替代对象来调用
            console.log(Array.prototype.join.apply(arguments, ["-"]));
            console.log(Array.prototype.join.call(arguments, "-"));
        }
        fun2(1,2,3,4);

        //应用4:借用构造函数实现继承
        function Persion() {
            this.name="张三";
            this.age=18;
        }
        function Student() {
            Persion.apply(this);
        }
        var stu=new Student();
        console.log(stu);


        //第二个用途:第二个到第N个参数的处理
        function fun1(name,work) {
            console.log("名字为"+name+";年龄为"+this.age+"职业"+work);
        }
        var obj1={
            age:30
        };
        /*
        * apply和call第二个参数都是函数的参数
        * apply是传递的数组,执行的时候是将数组遍历然后作为参数传递。
        * call传递的是分开的参数
        * */
        fun1.apply(obj1,["张三","金融"]);
        fun1.call(obj1,"张三","金融");

        //应用2:apply的遍历
        window.onload=function () {
            var divs=document.querySelectorAll("div");
            var spans=document.querySelectorAll("span");
            var arr=[];
            arr.push.apply(arr,divs);
            arr.push.apply(arr,spans);

            for(var i=0;i<arr.length;i++){
                arr[i].style.backgroundColor="red";
            }
        }

        //应用3:求最大值
        var arr1=[3,6,1,78,23];
        console.log(Math.max.apply(null, arr1));
    </script>
    <style>
        div,span{
            display: inline-block;
            width: 50px;
            height: 50px;
            border: 1px solid pink;
        }
    </style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<br>
<span></span>
<span></span>
<span></span>
<span></span>
</body>
</html>
原文地址:https://www.cnblogs.com/zhuyapeng/p/8434664.html