每个函数都包含两个非继承而来的方法,call()和apply(),可以改变函数内部this的指向
1、apply
用另一个对象替换当前对象,接收两个参数,第一个参数表示需要绑定的this变量,第二个参数是数组,表示函数本身的参数
var xiaoming = { "name":"xiaoming", "birth":1990, "age":function(){ var y = new Date().getFullYear(); return y - this.birth ; } } var fn = xiaoming.age; alert(fn.apply(xiaoming,[])); //26 alert(fn());//NaN
变量fn获取到age对应的函数,此时函数中的this指向window,故fn()返回NaN,调用apply使fn中的this指向xiaoming,故返回26
2、call
call()方法与apply()方法类似,区别是apply将参数打包成数组传入,而call方法是把参数按顺序传入
对于普通方法的调用,通常把this绑定为null
alert(Math.max.apply(null,[3,2,5,10])); alert(Math.max.call(null,3,2,5,10));
3、bind
bind用来改变函数的作用域指向,但是它不立即执行,而是通过调用执行