js中call和apply的用法
call的用方法:
- var obj = {
- arg1: 1,
- arg2: 2
- }
- function f(a,b){
- return this.arg1 + this.arg2 + a + b;
- }
- var r = f.call(obj,3,4); // r =10
等同于:
- var obj = {
- arg1: 1,
- arg2: 2
- }
- function f(a,b){
- return this.arg1 + this.arg2 + a + b;
- }
- obj.m = f;
- var r = obj.m(3,4);
- delete obj.m;
applay和call方法相似,只不过要传递的参数以数组的形式制定上面的代码调用apply可写成:
- var obj = {
- arg1: 1,
- arg2: 2
- }
- function f(a,b){
- return this.arg1 + this.arg2 + a + b;
- }
- var r = f.apply(obj,[3,4]); // r =10
只为成功找方法,不为失败找理由!