1,通过调用call()函数
call第一个作用可以调用函数 第二个可以改变函数内this的指向 call也可以实现继承
var o={ name:"td" } function fn(){ console.log(this) } fn.call() //指向window fn.call(o) //指向o这个对象 function father(uname,age){ this.uname=uname this.age=age } function son(uname,age){ father.call(this,uname,age)//this指向son } var son1=new son("ldh",11) console.log(son1)//son {uname: "ldh", age: 11}
2,通过调用apply()函数
可以改变this的指向,参数必须为数组或者伪数组,第一个参数为this的指向,第二个为数组
我们也可以用apply借助于数学内置对象求最大值
var o={
name:"td"
}
function fn(){
console.log(this)
}
fn.apply() //指向window
fn.apply(o) //指向o这个对象
var arr=[1,2,3]
var max=Math.apply(Math,arr)
var min=Math.apply(Math,arr)
console.log(max,min)//3 ,1
3,bind方法
bind方法不会调用函数但是能改变函数内的this指向
bind(this.arg,arg1,arg2)
this.arg 在函数运行时指定的this的值
agr1 arg2 传递的参数
返回指定的this值和初始化参数改造原函数拷贝
var o={ name:'and' } function fn(a,b){ console.log(this) } var f=fn.bind(o,1,2) f()