您的位置:首页 > Web前端 > JavaScript

javascript中call,apply,callee,caller用法实例分析

2019-07-24 09:40 1871 查看

本文实例讲述了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(); // 输出函数自身的字符串表达式

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结

希望本文所述对大家JavaScript程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息