JavaScript中call()和apply()方法的使用

来源:互联网 发布:易语言读mysql数据库 编辑:程序博客网 时间:2024/06/16 02:34

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()还有更加高大上的用法,例如用于链接构造器,这个功能可以查看这里:点击打开链接
原创粉丝点击