前言
在上一章js文章中,函数节流(throttle)中用到了apply()方法,对此自己有点儿疑义,于是想弄明白apply和call的用法。一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向。
apply
function Person(name,age){
this.name=name;
this.age=age;
}
function Students(name,age,grade){
console.log(this)
Person.apply(this,arguments);
console.log(this)
this.grade=grade;
console.log(this)
}
var student=new Students('a',12,12);
console.log(student)
apply方法是为了改变this的指向,让Students来继承Person方法和属性,而第二个参数arguments是一个数组参数。第一次打印this的时候,this是指向Students,并且此时的Students里面是没任何东西的,通过Person.apply(this,arguments);,再去看this的结果的时候,Students已经拥有了Person方法的属性。
image.png
call
function Person(name,age){
this.name=name;
this.age=age;
}
function Students(name,age,grade){
console.log(this)
Person.call(this,name,age);
console.log(this)
this.grade=grade;
}
var student=new Students('a',12,12);
console.log(student)
与apply方法不一样的是,第二个arguments是接受的连续参数。








网友评论