前言
在上一章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
方法的属性。

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
是接受的连续参数。
网友评论