Javascript中的this绑定

在Javascript里,函数被调用的时候,除了接受声明是定义的形式参数,每一个函数还接受两个附加的参数:this和arguments。而this的具体值则取决于其调用模式。

  * 方法调用模式:this被绑定到该对象。

  * 函数调用模式:this被绑定到全局对象,网页的情况下绑定到window

  * 构造器调用模式:this被绑定到新生成的对象。

  * 事件处理调用模式分两种情况:参照

      * this被绑定到全局对象

1 <script type="text/javascript"> 
2 function click_handler() {
3 alert(this); // alerts the window object
4 }
5 </script>
6 ...
7 <button id='thebutton' onclick='click_handler()'>Click me!</button>

      * this被绑定到DOM对象

 1 <script type="text/javascript"> 
2 function click_handler() {
3 alert(this); // alerts the button DOM node
4 }
5
6 function addhandler() {
7 document.getElementById('thebutton').onclick = click_handler;
8 }
9
10 window.onload = addhandler;
11
12 </script>
13 ...
14 <button id='thebutton'>Click me!</button>

由于函数调用的上下文的变化导致了this的不确定性。为了更好的明确this上下文,可以使用call和apply两个方法来明确化this绑定的值。

call和apply的区别仅仅在于参数上的区别:call接受任意参数列表,apply接受一个参数数组对象。这也使得apply可以接受arguments作为其第二参数。

1 func.call(obj1,var1,var2,var3)
2
3 func.apply(obj1, [var1,var2,var3])
4
5 func.apply(obj1, arguments)

但是call和apply方式都是立即执行的,如果需要后来使用的话,就不能满足条件,如下例,其中13行和14行无论是否使用call都无法得到我们需要的值(42)。

 1 <script type="text/javascript"> 
2 function BigComputer(answer) {
3 this.the_answer = answer;
4 this.ask_question = function () {
5 alert(this.the_answer);
6 }
7 }
8
9 function addhandler() {
10 var deep_thought = new BigComputer(42),
11 the_button = document.getElementById('thebutton');
12
13 //the_button.onclick = deep_thought.ask_question;
14 the_button.onclick = deep_thought.ask_question.call(deep_thought);
15 }
16
17 window.onload = addhandler;
18 </script>

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

1 Function.prototype.bind = function(object) { 
2 var method = this;
3 return function() {
4 method.apply(object, arguments);
5 }
6 }

具体实现上利用闭包特性,返回来的函数引用在执行的时候,可以访问创建该函数引用时的method和object两个参数,而不是使用this,this在执行的时候会重新被绑定,而不是原来的method这个值。

原文地址:https://www.cnblogs.com/foxracle/p/2185284.html