JavaScript中的函数也是对象,和其余JS对象同样也能够包含方法,其中Call和Apply就是其中比较重要的方法,能够用来间接的调用函数。这两个方法容许显式制定调用所需的this值,也就是说全部函数能够做为任何对象的方法来使用,哪怕这个函数不是那个对象的方法。数组
Call方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Apply方法:app
语法:apply([thisObj[,argArray]])函数
Call和Apply方法做用相同,但从以上语法来看,他们传入的参数方式不一样,两个方法第一个参数都是须要调用方法的对象(thisObj),函数所须要的实参Call方法是以列表形式传入,而Apply方法则须要以数组形式传入实参。this
实例:spa
1 function People(name, age) { 2 3 this.name = name; 4 this.age = age; 5 this.showName = function () { 6 7 console.log(this.name); 8 9 } 10 } 11 12 13 function Student(name, age) { 14 15 this.name = name; 16 this.age = age; 17 this.showAge = function () { 18 19 console.log(this.age); 20 } 21 } 22 23 24 var people = new People("peopleName", 20); 25 var student = new Student("studentName", 10); 26 27 people.showName.call(student);//输出studentName
在以上代码中,一样能够使用people.showName.apply(student),输出结果仍是studentName。code