javascript一则
2009-01-17 14:57 wlstyle 阅读(234) 评论(0) 收藏 举报 1 var name='tony';
2 function scopeTest(){
3 alert(this.name);
4 }
5 //在window的作用域中调用这个方法
6 scopeTest();
7 //输出值为 tony
8 var obj={
9 name:'jack',
10 otherscopeTest:function(){
11 alert(this.name);
12 }
13 }
14 obj.otherscopeTest();
15 //输出值为jack
16 window.test= obj.otherscopeTest;
17 test();
18 //输出值为tony
2 function scopeTest(){
3 alert(this.name);
4 }
5 //在window的作用域中调用这个方法
6 scopeTest();
7 //输出值为 tony
8 var obj={
9 name:'jack',
10 otherscopeTest:function(){
11 alert(this.name);
12 }
13 }
14 obj.otherscopeTest();
15 //输出值为jack
16 window.test= obj.otherscopeTest;
17 test();
18 //输出值为tony
在17行的输出居然是tony.这主要是js的函数的作用域不同而产生的一个问题.当window.test引用obj.otherscopeTest的时候这里的this对象表示的是window对象.而非先前的obj这个对象.这就导致了最后输出的不同.那么如何才能将函数的执行环境固定为某个特定的范围呢?这里引用prototype.js里的绑定方法
1 Function.prototype.bind= function(){
2 var fn=this,args=Array.prototype.slice.call( arguments),object= args.shift();
3 return function(){
4 return fn.apply(object,args.concat(Array.prototype.slice.call( arguments)));
5 }
2 var fn=this,args=Array.prototype.slice.call( arguments),object= args.shift();
3 return function(){
4 return fn.apply(object,args.concat(Array.prototype.slice.call( arguments)));
5 }
6 }
然后测试一下这个bind函数的作用
1 name='jack';
2 var personDetail={
3 name:'tony',
4 age:'30'
5 }
6 function sayName(){
7 alert(this.name);
8 }
9 window.bindsayName=sayName.bind(personDetail,22);
10 bindsayName();//output tony
2 var personDetail={
3 name:'tony',
4 age:'30'
5 }
6 function sayName(){
7 alert(this.name);
8 }
9 window.bindsayName=sayName.bind(personDetail,22);
10 bindsayName();//output tony
这时候输出的是tony而不是jack,这里就是bind函数的功劳了 他将此函数的作用域绑定在了PersonDetail这个作用域中 .
浙公网安备 33010602011771号