javascript中调用上下文信息的方法
一.使用函数自身
1 <script type="text/javascript">
2 function oFunc(){
3 alert(oFunc.toString());
4 };
5 oFunc();
6 </script>
2 function oFunc(){
3 alert(oFunc.toString());
4 };
5 oFunc();
6 </script>
二.使用函数caller属性
其表示调用当前函数的上层函数。
1 <script type="text/javascript">
2 function WhoCallMe(){
3 alert("My caller is "+WhoCallMe.caller);
4 };
5 function CallerA(){WhoCallMe();};
6 function CallerB(){WhoCallMe();};
7
8 WhoCallMe();//My caller is null
9 CallerA();//my caller is function CallerA(){WhoCallMe();};
10 CallerB();//my caller is function CallerB(){WhoCallMe();};
11 </script>
2 function WhoCallMe(){
3 alert("My caller is "+WhoCallMe.caller);
4 };
5 function CallerA(){WhoCallMe();};
6 function CallerB(){WhoCallMe();};
7
8 WhoCallMe();//My caller is null
9 CallerA();//my caller is function CallerA(){WhoCallMe();};
10 CallerB();//my caller is function CallerB(){WhoCallMe();};
11 </script>
三.使用this
1 <script type="text/javascript">
2 function WhoAmI(){
3 alert("I'm "+this.name+" of "+typeof(this));
4 };
5 WhoAmI();
6
7 var SteveJobs = {name:"Steve Jobs"};
8 SteveJobs.WhoAmI=WhoAmI;
9 SteveJobs.WhoAmI();//this是Steve Jobs
10
11 var BillGates = {name:"Bill Gates"};
12 BillGates.WhoAmI=WhoAmI;
13 BillGates.WhoAmI();//this是Bill Gates
14
15 </script>
2 function WhoAmI(){
3 alert("I'm "+this.name+" of "+typeof(this));
4 };
5 WhoAmI();
6
7 var SteveJobs = {name:"Steve Jobs"};
8 SteveJobs.WhoAmI=WhoAmI;
9 SteveJobs.WhoAmI();//this是Steve Jobs
10
11 var BillGates = {name:"Bill Gates"};
12 BillGates.WhoAmI=WhoAmI;
13 BillGates.WhoAmI();//this是Bill Gates
14
15 </script>
四.使用Call
1 <script type="text/javascript">
2 function WhoAmI(){
3 alert("I'm "+this.name+" of "+typeof(this));
4 };
5 WhoAmI();
6
7 var SteveJobs = {name:"Steve Jobs"};
8
9 var BillGates = {name:"Bill Gates"};
10
11 WhoAmI.call(SteveJobs);//输出I'm Steve Jobs of Object
12 WhoAmI.call(BillGates);//输出I'm Bill Gates of Object
13
14 </script>
2 function WhoAmI(){
3 alert("I'm "+this.name+" of "+typeof(this));
4 };
5 WhoAmI();
6
7 var SteveJobs = {name:"Steve Jobs"};
8
9 var BillGates = {name:"Bill Gates"};
10
11 WhoAmI.call(SteveJobs);//输出I'm Steve Jobs of Object
12 WhoAmI.call(BillGates);//输出I'm Bill Gates of Object
13
14 </script>