JavaScript中call/apply 区别

一、call -----> 改变this指向;

在函数执行时有个隐式转换:

     function test(){}
     test();             // test(); -----> (相当于) test.call();(内部处理)
1> 用call改变一个函数里this的指向:
    function Person(name,age){
        //this == obj;
        this.name = name;
        this.age = age;
    }
    var person = new Person('wang',100);
    var obj = {}
    Person.call(obj);          // ----> 使Person中this指向obj
    Person.call(obj,'li',200);   // 改变this指向、传参

console里输入:

把person对象中的属性拷贝到obj对象里

2> 形参(属性)“共享”

 function Person(name,age,sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    function Student(name,age,sex,tel,grade){
        Person.call(this,name,age,sex);          // 覆盖Person里的全部this,不可选择。只能把Person里的属性全部涵盖(减少代码量 不用再重复写:this.name = name;)
        this.tel = tel;
        this.grade = grade;
    }
    var student = new Student('wang',111,'male',157,2018);

二、apply ----> 改变this指向

    function Wheel(wheelSize,style){
        this.style = style;
        this.wheelSize = wheelSize;
    }
    function sit(c,sitColor){
        this.c = c;
        this.sitColor = sitColor;
    }
    function Model(height,width,len){
        this.height = height;
        this.width = width;
        this.len = len;
    }
    function Car(wheelSize,style,c,sitColor,height,width,len){
        Wheel.apply(this,[wheelSize,style]);              // 减少代码量,apply是用数组形式表示(arguments)
        sit.apply(this,[sitColor]);
        Model.apply(this,[height,width,len]);
    }
    var car = new Car(100,'五彩','真皮','red',1800,1900,4900);


call/apply的区别:通过上面代码可看出:

call需要把实参按形参的个数传进去

apply需要传一个arguments


猜你喜欢

转载自blog.csdn.net/qq_42062727/article/details/80542500