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

Javascript中的this绑定介绍

2011-09-22 00:00 1266 查看
而this的具体值则取决于其调用模式。
* 方法调用模式:this被绑定到该对象。
* 函数调用模式:this被绑定到全局对象,网页的情况下绑定到window
* 构造器调用模式:this被绑定到新生成的对象。
* 事件处理调用模式分两种情况:参照
* this被绑定到全局对象
<script type="text/javascript"> 
function click_handler() { 
alert(this); // alerts the window object 
} 
</script> 
... 
<button id='thebutton' onclick='click_handler()'>Click me!</button>

* this被绑定到DOM对象
<script type="text/javascript"> 
function click_handler() { 
alert(this); // alerts the button DOM node 
} 
function addhandler() { 
document.getElementById('thebutton').onclick = click_handler; 
} 
window.onload = addhandler; 
</script> 
... 
<button id='thebutton'>Click me!</button>

由于函数调用的上下文的变化导致了this的不确定性。为了更好的明确this上下文,可以使用call和apply两个方法来明确化this绑定的值。
call和apply的区别仅仅在于参数上的区别:call接受任意参数列表,apply接受一个参数数组对象。这也使得apply可以接受arguments作为其第二参数。
func.call(obj1,var1,var2,var3) 
func.apply(obj1, [var1,var2,var3]) 
func.apply(obj1, arguments)

但是call和apply方式都是立即执行的,如果需要后来使用的话,就不能满足条件,如下例,其中13行和14行无论是否使用call都无法得到我们需要的值(42)。
<script type="text/javascript"> 
function BigComputer(answer) { 
this.the_answer = answer; 
this.ask_question = function () { 
alert(this.the_answer); 
} 
} 
function addhandler() { 
var deep_thought = new BigComputer(42), 
the_button = document.getElementById('thebutton'); 
//the_button.onclick = deep_thought.ask_question; 
the_button.onclick = deep_thought.ask_question.call(deep_thought); 
} 
window.onload = addhandler; 
</script>

这个时候就是bind方法大显身手的时候(该方法已经在ECMA-262第五版已经加入),最早出现在Prototype框架中(未确认过)。bind和call,apply一样,也是变更函数执行的上下文,也即函数执行时this的值。不同的在于,它返回一个函数引用以供后续使用,其简单实现如下:
Function.prototype.bind = function(object) { 
var method = this; 
return function() { 
method.apply(object, arguments); 
} 
}

具体实现上利用闭包特性,返回来的函数引用在执行的时候,可以访问创建该函数引用时的method和object两个参数,而不是使用this,this在执行的时候会重新被绑定,而不是原来的method这个值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: