您的位置:首页 > 移动开发

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

2016-03-31 00:52 639 查看
实践一: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(); // 输出函数自身的字符串表达式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: