What is the difference between call and apply?

前端 未结 24 1654
太阳男子
太阳男子 2020-11-21 07:12

What is the difference between using call and apply to invoke a function?

var func = function() {
  alert(\'hello!\');
};
         


        
24条回答
  •  终归单人心
    2020-11-21 07:44

    A well explained by flatline. I just want to add a simple example. which makes it easy to understand for beginners.

    func.call(context, args1 , args2 ); // pass arguments as "," saprated value
    
    func.apply(context, [args1 , args2 ]);   //  pass arguments as "Array"
    

    we also use "Call" and "Apply" method for changing reference as defined in code below

        let Emp1 = {
            name: 'X',
            getEmpDetail: function (age, department) {
                console.log('Name :', this.name, '  Age :', age, '  Department :', department)
            }
        }
        Emp1.getEmpDetail(23, 'Delivery')
    
        // 1st approch of chenging "this"
        let Emp2 = {
            name: 'Y',
            getEmpDetail: Emp1.getEmpDetail
        }
        Emp2.getEmpDetail(55, 'Finance')
    
        // 2nd approch of changing "this" using "Call" and "Apply"
        let Emp3 = {
            name: 'Z',
        }
    
        Emp1.getEmpDetail.call(Emp3, 30, 'Admin')        
    // here we have change the ref from **Emp1 to Emp3**  object
    // now this will print "Name =  X" because it is pointing to Emp3 object
        Emp1.getEmpDetail.apply(Emp3, [30, 'Admin']) //

提交回复
热议问题