javascript中的call,apply,callee,caller等的分析

实践一:call,apply 用来让一个对象去调用本不属于自己的方法,两者都可以传递参数,call的参数是列表形式,apply的参数是数组形式

var person = {
  "name":"Tom",
  "say":function(){
    console.log("person say");
  },
  "count":function(x,y,z){
    console.log('x= ' + x + ', y= ' + y + ', z= ' + z);
  },
  "sayName":function(){
    console.log(this.name);
  }
}
// 下面的示例是数组 arr 去调用person的say方法 , 这里call用来让数组调用本不属于它自己的方法
var arr = [1,2];
person.say.call(arr);

// call 还可以传递参数
person.count.call(arr,1,2,3); // x= 1, y= 2, z= 3
// apply 还可以这样
person.count.apply(arr,[1,2,3]); // x= 1, y= 2, z= 3
实践二:call,apply 用来修改this,   同样引用上例的person对象

var program = {"name":"AlphaGo"}
person.sayName.call(program); // AlphaGo
person.sayName.apply(program); // AlphaGo
实践三:call,apply把伪数组转换为数组

// call,apply 把伪数组转换为数组
var wArr = {0:"hello",1:"world","length":2};
var arr1 = Array.prototype.slice.call(wArr);
var arr2 = Array.prototype.slice.apply(wArr);
console.log(arr1); // [hello,world]
console.log(arr2); // [hello,world]

这里找到一篇详细的  关于伪数组的博客

实践四:单纯的arguments对象

// 有关arguments
function count(a,b,c){
  console.log(arguments.length);
  if(count.length === arguments.length) {
    console.log('实际参数与形参个数相同');
  }else{
    console.log('实际参数与形参个数不同');
  }
}
count(1,2,3); // 实际参数与形参个数相同
count(1,2); // 实际参数与形参个数不同
/*
这里count.length 表示形参个数
arguments.length 表示实参个数
*/
实践五:caller 用于查看,函数本身被哪个函数调用

function fn1(){
  if(fn1.caller){
    console.log(fn1.caller.name + " 是函数fn1的调用者");
  }else{
    console.log("直接执行");
  }
}
function fn2(){
  fn1();
};
fn2(); // fn2是是函数fn1的调用者
实践六:callee 返回正被执行的 Function 对象,常用于匿名函数的递归与arguments一起配合使用。
var sum = function(n){
  if(n>0) {
    return n + arguments.callee(n-1);
  }
  return 0;
};
var total = sum(10);
console.log(total); // 55

// arguments.callee 代指函数自身。
function test(){
  console.log(arguments.callee);
}
test(); // 输出函数自身的字符串表达式

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值