apply()和call()用法

文章目录

每个函数都有两个非继承的方法:apply()和call()。这两个方法都是在特定作用域中调用函数,实际上等于设置函数体内this对象的值。

方法定义

1、apply()方法——apply([thisObj[,argArray]])

apply()接收两个参数:一个是运行函数的作用域,另一个是参数数组。其中第二个参数可以是Array的实例,也可以是arguments对象。

2、call()方法——call([thisObj[,arg1[, arg2[, [,.argN]]]]])

与apply作用相同,区别在于接收参数方式不同。第一个参数this的值没有变化,其余参数是以列举的方式直接传递给函数。

作用

1、扩充函数赖以运行的作用域

      
      
1
2
3
4
5
6
7
8
9
10
      
      
window.color="red";
var o={color:"blue"};
function sayColor(){
alert(this.color)
}
sayColor(); //red
sayColor.call(this); //red
sayColor.call(window); //red
sayColor.call(o); //blue

sayColor.call(o)与o.sayColor()效果一样,但是使用call()(或apply())是的对象不需要与方法有任何耦合关系。

2、实现继承

大专栏   apply()和call()用法ass="highlight plain">
      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
function Animal(name){
this.name=name;
this.showName=function(){
alert(this.name);
}
}
function Cat(name){
Animal.call(this,name);
}
var cat=new Cat('Black Cat');
cat.showName(); //Black Cat

3、实现多重继承

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
      
      
var s1=function(name){
this.name=name;
}
var s2=function(sex){
this.sex=sex;
}
var s3=function(age){
this.age=age;
}
var Student=function(name,sex,age,score){
s1.call(this,name);
s2.call(this,sex);
s3.call(this,age);
this.score=score;
}
Student.prototype.construction=Student;
var s=new Student('jack','male','32','100');
console.log(s.name); //jack
console.log(s.sex); //male
console.log(s.age); //32
console.log(s.score); //100

猜你喜欢

转载自www.cnblogs.com/sanxiandoupi/p/11692167.html