1 call()方法
call()方法调用一个函数,其具有一个指定的this值和分别地提供参数,其参数需要把实参按照形参的个数传进去,其与apply()方法的区别就是call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组。
其语法如下:
function.call(this,arg1,arg2, ...);
返回结果是指定的this值和参数列表。下面编写一个关于个人信息的例子,并将结果打印到控制台:
function Man(name, nationality, sex, age, wealth, interest){
this.name = name;
this.nationality = nationality;
this.sex = sex;
this.age = age;
this.wealth = wealth;
this.interest = interest;
}
function Information(name, nationality, sex, age, wealth, interest, wife, son){
Man.call(this, name, nationality, sex, age, wealth, interest);
this.wife = wife;
this.son = son;
}
var bruce = new Information("Bruce", "USA", "male", "40", "$10 millions", "basketball","Jane", "Tom");
console.log("姓名:" + bruce.name);
console.log("国籍:" + bruce.nationality);
console.log("性别:" + bruce.sex);
console.log("年龄:" + bruce.age);
console.log("财富值:" + bruce.wealth);
console.log("兴趣:" + bruce.interest);
console.log("妻子:" + bruce.wife);
console.log("儿子:" + bruce.son);
2 apply()方法
appay()方法调用一个函数,其具有一个this值,以及作为一个数组提供的参数,其与call()方法的区别已经在上面讲了,这里将不再赘述。其语法如下:
function.apply(this,[arg1,arg2, ...]);
其使用方法代码如下:
function Man(name, nationality, sex, age, wealth, interest){
this.name = name;
this.nationality = nationality;
this.sex = sex;
this.age = age;
this.wealth = wealth;
this.interest = interest;
}
function Information(name, nationality, sex, age, wealth, interest, wife, son){
Man.apply(this, [name, nationality, sex, age, wealth, interest]);
this.wife = wife;
this.son = son;
}
var bruce = new Information("Bruce", "USA", "male", "40", "$10 millions", "basketball","Jane", "Tom");
console.log("姓名:" + bruce.name);
console.log("国籍:" + bruce.nationality);
console.log("性别:" + bruce.sex);
console.log("年龄:" + bruce.age);
console.log("财富值:" + bruce.wealth);
console.log("兴趣:" + bruce.interest);
console.log("妻子:" + bruce.wife);
console.log("儿子:" + bruce.son);
输出结果与call()方法一致:
当然,apply()还有更加高大上的用法,例如用于链接构造器,这个功能可以查看这里:点击打开链接