JavaScript的this,call(),apply(),bind()

來源:互聯網
上載者:User
文章目錄
  • Complications

為了建立一個scope chain, 每個JavaScript的代碼執行內容都提供了this關鍵字。In its most common usage, this
serves as an identity function, providing our neighborhoods a way of
referring to themselves. We can’t always rely on that behavior,
however: Depending on how we get into a particular neighborhood, this might mean something else entirely. In fact, how we get into the neighborhood is itself exactly what this generally refers to. 需要注意特殊的四種情況:

  • Calling an Object’s Method

    在典型的物件導向編程時,我們需要一種方式去指向和引用我們調用的對象. this serves the purpose admirably, providing our objects the ability to examine themselves, and point at their own properties.

     var deep_thought = {<br /> the_answer: 42,<br /> ask_question: function () {<br /> return this.the_answer;<br /> }<br /> };</p><p> var the_meaning = deep_thought.ask_question(); 

    This example builds an object named deep_thought, sets its the_answer property to 42, and creates an ask_question method. When deep_thought.ask_question() is executed, JavaScript establishes an execution context for the function call, setting this to the object referenced by whatever came before the last ”.”, in this case: deep_thought. The method can then look in the mirror via this to examine its own properties, returning the value stored in this.the_answer: 42.

  • Constructor

    Likewise, when defining a function to be used as a constructor with the new keyword, this can be used to refer to the object being created. Let’s rewrite the example above to reflect that scenario:

     <mce:script type="text/javascript"><!--<br /> function BigComputer(answer) {<br /> this.the_answer = answer;<br /> this.ask_question = function () {<br /> return this.the_answer;<br /> }<br /> }</p><p> var deep_thought = new BigComputer(42);<br /> var the_meaning = deep_thought.ask_question();</p><p>// --></mce:script>

    Instead of explicitly creating the deep_thought object, we’ll write a function to create BigComputer objects, and instantiate deep_thought as an instance variable via the new keyword. When new BigComputer() is executed, a completely new object is created transparently in the background. BigComputer is called, and its this keyword is set to reference that new object. The function can set properties and methods on this, which is transparently returned at the end of BigComputer’s execution.

    Notice, though, that deep_thought.the_question() still works just as it did before. What’s going on there? Why does this mean something different inside the_question than it does inside BigComputer? Put simply, we entered BigComputer via new, so this meant “the new object.” On the other hand, we entered the_question via deep_thought, so while we’re executing that method, this means “whatever deep_thought refers to”. this is not read from the scope chain as other variables are, but instead is reset on a context by context basis.

  • Function Call

    What if we just call a normal, everyday function without any of this fancy object stuff? What does this mean in that scenario?<mce:script type="text/javascript"><!--<br /> function test_this() {<br /> return this;<br /> }<br /> var i_wonder_what_this_is = test_this();</p><p>// --></mce:script> 

     

    In this case, we weren’t provided a context by new, nor were we given a context in the form of an object to piggyback off of. Here, this defaults to reference the most global thing it can: for web pages, this is the window object.

  • Event Handler

    For a more complicated twist on the normal function call, let’s say that we’re using a function to handle an onclick event. What does this mean when the event triggers our function’s execution? Unfortunately, there’s not a simple answer to this question.

    If we write the event handler inline, this refers to the global window object:

      <mce:script type="text/javascript"><!--<br /> function click_handler() {<br /> alert(this); // alerts the window object<br /> }</p><p>// --></mce:script> 
     ...
     <button id='thebutton' onclick='click_handler()'>Click me!</button> 

    However, when we add an event handler via JavaScript, this
    refers to the DOM element that generated the event. (Note: The event
    handling shown here is short and readable, but otherwise poor. Please
    use a real addEvent function instead.):

     <script type="text/javascript">
      <mce:script type="text/javascript"><!--<br /> function click_handler() {<br /> alert(this); // alerts the button DOM node<br /> }</p><p> function addhandler() {<br /> document.getElementById('thebutton').onclick = click_handler;<br /> }</p><p> window.onload = addhandler;</p><p>// --></mce:script> 
     ...
     <button id='thebutton'>Click me!</button> 

Complications

Let’s run with that last example for a moment longer. What if instead of running click_handler, we wanted to ask deep_thought a question every time we clicked the button? The code for that seems pretty straightforward; we might try this:

<mce:script type="text/javascript"><!--<br /> function BigComputer(answer) {<br /> this.the_answer = answer;<br /> this.ask_question = function () {<br /> alert(this.the_answer);<br /> }<br /> }</p><p> function addhandler() {<br /> var deep_thought = new BigComputer(42),<br /> the_button = document.getElementById('thebutton');</p><p> the_button.onclick = deep_thought.ask_question;<br /> }</p><p> window.onload = addhandler;<br />// --></mce:script> 

對上面的代碼,我們期望點擊按鈕, deep_thought.ask_question被執行,我們得到返回結果“42.” 但為什麼得到的結果反而是undefined?哪裡錯了?

The problem is simply this: We’ve passed off a reference to the ask_question
method, which, when executed as an event handler, runs in a different
context than when it’s executed as an object method. 簡而言之,ask_question 中的this關鍵字是指向產生事件的DOM元素節點,而不是BigComputer對象. DOM元素節點並沒有the_answer屬性,所以返回結果是undefined而不是“42.” setTimeout exhibits similar behavior, delaying the execution of a function while at the same time moving it out into a global context.

This issue crops up all over the place in our programs, and it’s a
terribly difficult problem to debug without keeping careful track of
what’s going on in all the corners of your program, especially if your
object has properties that do exist on DOM elements or the window object.

Manipulating Context With .apply() and .call()

We really do want to be able to ask deep_thought a question when we click the button, and more generally, we do want to be able to call object methods in their native context when responding to things like events and setTimeout calls. Two little-known JavaScript methods, apply and call, indirectly enable this functionality by allowing us to manually override the default value of this when we execute a function call. Let’s look at call first:

<mce:script type="text/javascript"><!--<br /> var first_object = {<br /> num: 42<br /> };<br /> var second_object = {<br /> num: 24<br /> };</p><p> function multiply(mult) {<br /> return this.num * mult;<br /> }</p><p> multiply.call(first_object, 5); // returns 42 * 5<br /> multiply.call(second_object, 5); // returns 24 * 5<br />// --></mce:script> 

In this example, we first define two objects, first_object and second_object, each with a num property. Then we define a multiply function that accepts a single argument, and returns the product of that argument, and the num property of its this object. If we called that function by itself, the answer returned would almost certainly be undefined, since the global window object doesn’t have a num property unless we explicitly set one. We need some way of telling multiply what its this keyword ought refer to; the call method of the multiply function is exactly what we’re looking for.

 call方法的第一個參數定義了this關鍵字在被呼叫者法的執行內容中指向和對象,call方法的剩餘參數則是被呼叫者法的參數。因此當multiply.call(first_object, 5)被執行, multiply函數被調用, 5 為傳入方法的第一個參數, this 執行 first_object對象。 Likewise, when multiply.call(second_object, 5) is executed, the multiply function is called, 5 is passed in as the first argument, and the this keyword is set to refer to object second_object.

apply方法和 call方法基本一致,但是允許你以數組的形式向被調用的函數傳遞參數,
which can be quite useful when programatically generating function
calls. Replicating the functionality we just talked about using apply is trivial:

<mce:script type="text/javascript"><!--<br /> ...</p><p> multiply.apply(first_object, [5]); // returns 42 * 5<br /> multiply.apply(second_object, [5]); // returns 24 * 5<br />// --></mce:script> 

apply and call are very useful on their
own, and well worth keeping around in your toolkit, but they only get
us halfway to solving the problem of context shifts for event handlers.
It’s easy to think that we could solve the problem by simply using call to shift the meaning of this when we set up the handler:

function addhandler() {<br /> var deep_thought = new BigComputer(42),<br /> the_button = document.getElementById('thebutton');</p><p> the_button.onclick = deep_thought.ask_question.call(deep_thought);<br />} 

上面的代碼仍然存在問題: call是立即執行函數的,因此我們提供的 onclick handler是函數的執行結果而不是函數本身.我們需要JavaScript的另一個特性來解決這個問題:bind方法。

The Beauty of .bind()

I’m not a huge fan of the Prototype JavaScript framework, but I am very much impressed with the quality of its code as a whole. In particular, one simple addition it makes to the Function object has had a hugely positive impact on my ability to manage the context in which function calls execute: bind performs the same general task as call, altering the context in which a function executes. The difference is that bind returns a function reference that can be used later, rather than the result of an immediate execution that we get with call.

If we simplify the bind function a bit to get at the
key concepts, we can insert it into the multiplication example we
discussed earlier to really dig into how it works; it’s quite an
elegant solution:

<mce:script type="text/javascript"><!--<br /> var first_object = {<br /> num: 42<br /> };<br /> var second_object = {<br /> num: 24<br /> };</p><p> function multiply(mult) {<br /> return this.num * mult;<br /> }</p><p> Function.prototype.bind = function(obj) {<br /> var method = this,<br /> temp = function() {<br /> return method.apply(obj, arguments);<br /> };</p><p> return temp;<br /> }</p><p> var first_multiply = multiply.bind(first_object);<br /> first_multiply(5); // returns 42 * 5</p><p> var second_multiply = multiply.bind(second_object);<br /> second_multiply(5); // returns 24 * 5<br />// --></mce:script> 

First, we define first_object, second_object, and the multiply function, just as before. With those taken care of, we move on to creating a bind method on the Function object’s prototype, which has the effect of making bind available for all functions in our program. When multiply.bind(first_object) is called, JavaScript creates an execution context for the bind method, setting this to the multiply function, and setting the first argument, obj, to reference first_object. So far, so good.

The real genius of this solution is the creation of method, set equal to this (the multiply function itself). When the anonymous function is created on the next line, method is accessible via its scope chain, as is obj (this couldn’t be used here, because when the newly created function is executed, this will be overwritten by a new, local context). This alias to this makes it possible to use apply to execute the multiply function, passing in obj to ensure that the context is set correctly. In computer-science-speak, temp is a closure that, when returned at the end of the bind call, can be used in any context whatsoever to execute multiply in the context of first_object.

This is exactly what we need for the event handler and setTimeout scenarios discussed above. The following code solves that problem completely, binding the deep_thought.ask_question method to the deep_thought context, so that it executes correctly whenever the event is triggered:

function addhandler() {<br /> var deep_thought = new BigComputer(42),<br /> the_button = document.getElementById('thebutton');</p><p> the_button.onclick = deep_thought.ask_question.bind(deep_thought);<br />} 

Beautiful.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.