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

来源:互联网 发布:淘宝网男士保暖上衣 编辑:程序博客网 时间:2024/06/01 18:25

实践一: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); // AlphaGoperson.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对象

// 有关argumentsfunction 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 0
原创粉丝点击