Home > Web Front-end > JS Tutorial > body text

js 中apply()与call()方法详解实例

WBOY
Release: 2016-06-01 09:54:57
Original
1039 people have browsed it

apply()和call(), 它们的作用都是将函数绑定到另外一个对象上去运行,两者仅在定义参数方式有所区别:
apply( thisArg , argArray );  
call( thisArg, [,arg1,arg2…] ] );

第一个参数表示所有函数内部的this指针都会被赋值为 thisArg,这可实现将函数作为另外一个对象的方法运行的目的.

<code><script type="text/javascript">
function sumFun(sum1,sum2){
    return sum1+sum2;
}

function applySum(sum1,sum2){
    //使用sumFun函数来完成一次调用,调用的参数就是applaySum这个函数的参数. 第二个参数表示一个数组。
    return sumFun.apply(this,arguments);
}
alert(applaySum(12,45));//运行结果是57;

function callSum(sum1,sum2){
    return sumFun.call(this,sum1,sum2);

}

alert(callSum(12,45));//运行结果是57;

</script></code>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!