一、apply()和call()
- 方法中如果没传入参数,或者是null,那么调用该方法的函数对象中的this就是默认的window
<script> function f1(x,y){ console.log(x+y+"======="+this) } f1.apply();//NaN=======[object Window] f1.apply(null);//NaN=======[object Window] f1.call();//NaN=======[object Window] f1.call(null);//NaN=======[object Window] </script>
- apply和call方法都可以让函数或者方法来调用,传入参数和函数自己调用的写法不一样,但是效果是一样的
<script> function f1(x,y){ console.log(x+y+"======="+this) } f1(10,20);//30=======[object Window] f1.apply(null,[10,20]);//30=======[object Window] f1.call(null,10,20);//30=======[object Window] </script>
- 作用:函数的调用,改变this的指向------在借用构造函数实现继承里也讲到过call方法
- 使用方法:只要想使用别的对象的方法,并且希望这个方法是当前对象
<script> //作用,调用函数,改变this的指向 function Person(age){ this.age=age; } Person.prototype.sayHi=function(x,y){ console.log((x+y)+"=======>"+this.age); }; function Student(age){ this.age=age; } var per=new Person(10);//Person的实例对象 var stu=new Student(100);//Student的实例对象 //sayHi方法是per实例对象原型里面的方法 //通过apply和call方法,stu调用了这个方法 //sayHi方法里面的this,由原来的per变成了stu per.sayHi.apply(stu,[10,20]);//30=======>100 per.sayHi.call(stu,10,20);//30=======>100 //写法 //函数名字/方法.apply(对象,[参数1,参数2,.....]) //函数名字/方法.call(对象,参数1,参数2,.......) </script>
- apply和call方法并不在函数这个实例对象中,而是在Function的原型prototype中
二、bind()
- bind方法是复制的意思,参数可以在复制的时候传进去,也可以在复制之后调用的时候传入进去
-
bind是在复制的时候改变this指向的,二apply和call是在调用的时候改变this指向的
-
使用方法:
-
函数名字.bind(对象,参数1,参数2,...)------>返回复制后的函数
-
方法名字.bind(对象,参数1,参数2,...)------>返回复制后的方法
<script> //使用方法: //1.函数名字.bind(对象,参数1,参数2,...)------>返回复制后的函数 function f1(x,y){ console.log(x+y); } var f2=f1.bind(null,10,20); f2();//30 //2.方法名字.bind(对象,参数1,参数2,...)------>返回复制后的方法 function Person(age){ this.age=age; } Person.prototype.show=function(){ console.log(this+"======"+this.age); }; function Student(age){ this.age=age; } var per=new Person(10); var stu=new Student(20); //stu对象使用bind复制了一份per的方法 var ff=per.show.bind(stu); ff();//[object Object]======20 </script>
- 应用:通过对象,调用方法,产生随机数
<script> //构造函数 function showRandom(){ //1-10的随机数 this.number=parseInt(Math.random()*10+1); } //原型方法 showRandom.prototype.show1=function(){ //定时器里的this是window,通过bind把this指向改变成为了实例对象 window.setInterval(this.show2.bind(this),1000); }; showRandom.prototype.show2=function(){ //显示随机数 console.log(this.number); }; //实例对象 var sr=new showRandom(); //调用方法,输出随机数字,调用一次,可以不停的产生(相同的)随机数字 sr.show1(); </script>