JavaScript中Call()以及Apply()的应用

apply()和call()的真正用武之地是能够扩充函数赖以运行的作用域

三点说明:

1、每个函数都包含两个非继承而来的方法:apply()和call()。

2、他们的用途相同,都是在特定的作用域中调用函数。

3、接收参数方面不同,apply()接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。
   call()方法第一个参数与apply()方法相同,但传递给函数的参数必须列举出来。

使用实例:

第一个实例:

        function print(a, b, c, d) {
            alert(a + b + c + d);
        }


        function example(a, b , c , d){ 
            //用call方式借用print,参数显式打散传递 
            print.call(this, a, b, c, d); 
            //用apply方式借用print, 参数作为一个数组传递, 
            //这里直接用JavaScript方法内本身有的arguments数组 
            print.apply(this, arguments); 
            //或者封装成数组 
            print.apply(this, [a, b, c, d]); 
            }
        //下面将显示”背光脚本”
        example("背","光","脚","本");     
View Code

第二个实例:

        function Animal(name)
        {
            this.name = name;
            this.showName = function () {
                alert(this.name);
            }
        }

        function Cat(name)
        {
            Animal.call(this, name);
        }
        
        var cat = new Cat("Black Cat");
        cat.showName();    
        function Animal(name)
        {
            this.name = name;
            this.showName = function () {
                alert(this.name);
            }
        }

        function Cat(name)
        {
            Animal.call(this, name);
        }

        Cat.prototype = new Animal();
        
        var cat = new Cat("Black Cat");
        cat.showName();

        alert(cat instanceof Animal);
原文地址:https://www.cnblogs.com/ck168/p/5459275.html