• js中call与apply的区别以及使用~


    今天看了一下call与apply的区别~~

    <!DOCTYPE html>
    <html>
    <head>
        <title>testCall</title>
    </head>
    <body>
    
    </body>
    <script type="text/javascript">
        /*
            apply,call 都是为了改变上下文this的指向
            两者的区别:
            Function.apply(thisobj,[arg1,arg2....])
            Function.call(thisobj,arg1,arg2....)
    
            thisobj:这个对象将代替Function类里this对象
            arg1,arg2....:这个是数组或类数组,apply方法把这个集合中的元素作为参数传递给被调用的函数
    
            非严格模式下,当我们第一个参数传递为null或undefined时,函数体内的this会指向默认的宿主对象,在浏览器中则是window
         */
        
        function test () {
            console.log(this == window)
        }
        test.call(null);   //true
        test.apply(null); //true
    
        /* 用法1:使用别人的方法 */
        var foo = {
            name: "ming",
            logName:function() {
                console.log(this.name)
            }
        }
        var bar={
          name:"xiaowang"
        };
    
        foo.logName.call(bar)
    
        /* 实现继承 */
        function Animal(name) {
            this.name = name;
            this.showName = function() {
                console.log(this.name)
            }
        }
    
        function Cat(name) {
            Animal.call(this,name)
            //this将替代Animal的this的指向
        }
        var cat = new Cat("paopao")
        cat.showName();
    
        function(){
          Array.prototype.push.call(arguments,4);
          console.log(arguments);//[1, 2, 3, 4]
        })(1,2,3)
    
        /* 数组合并 */
        var arr1=new Array("1","2","3");
        var arr2=new Array("4","5","6");
        Array.prototype.push.apply(arr1,arr2);  //相当于arr1调用了push方法,将arr2
        console.log(arr1);//["1", "2", "3", "4", "5", "6"]
    
        
    
    </script>
    </html>
  • 相关阅读:
    0529学习进度条
    0523-学习进度条
    0515-学习进度条
    实验三-进程模拟调度
    0501-学习进度条
    0424-学习进度条
    0422—操作系统作业调度
    0415-同学博客评价
    0414-复利计算再升级
    0409-学习进度条
  • 原文地址:https://www.cnblogs.com/Mrs-pao/p/7993646.html
Copyright © 2020-2023  润新知