技术控

    今日:0| 主题:63445
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Understanding "This" in JavaScript

[复制链接]
ポ奉ポ奉糖 发表于 2016-10-3 12:40:24
167 0
Conceptual Overview of “this”

  When a function is created, a keyword called    thisis created (behind the scenes), which links to the object in which the function operates.  
  The    thiskeyword’s value has nothing to do with the function itself, how the function is called determines this’s value  
  Default “this” context

  1. // define a function
  2. var myFunction = function () {
  3.   console.log(this);
  4. };
  5. // call it
  6. myFunction();
复制代码
What can we expect the    thisvalue to be? By default,    thisshould always be the window Object, which refers to the root—the global scope.  
  Object literals

  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };
复制代码
What would be the    thiscontext here?…  
  
       
  • this === myObject?   
  • this === window?   
  • this === anything else?  
  Well, the answer is    We do not know.  
  Remember    The this keyword’s value has nothing to do with the function itself, how the function is called determines the      thisvalue      
  Okay, let’s change the code a bit…
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var myObject = {
  5.   myMethod: myMethod
  6. };
复制代码
Is it clearer now?
  Of course, everything depends on how we call the function.
      myObjectin the code is given a property called    myMethod, which points to the    myMethodfunction. When the    myMethodfunction is called from the global scope, this refers to the window object. When it is called as a method of    myObject, this refers to    myObject.  
  1. myObject.myMethod() // this === myObject
  2. myMethod() // this === window
复制代码
This is called    implicit binding  
  Explicit binding

  Explicit binding is when we explicitly bind a context to the function. This is done with    call()or    apply()**  
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var myObject = {
  5.   myMethod: myMethod
  6. };
  7. myMethod() // this === window
  8. myMethod.call(myObject, args1, args2, ...) // this === myObject
  9. myMethod.apply(myObject, [array of args]) // this === myObject
复制代码
Which is more precedent, implicit binding or explicit binding?
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var obj1 = {
  5.     a: 2,
  6.     myMethod: myMethod
  7. };
  8. var obj2 = {
  9.     a: 3,
  10.     myMethod: myMethod
  11. };
  12. obj1.myMethod(); // 2
  13. obj2.myMethod(); // 3
  14. obj1.myMethod.call( obj2 ); // ?????
  15. obj2.myMethod.call( obj1 ); // ?????
复制代码
Explicit binding takes precedence over implicit binding, which means you should ask first if explicit binding applies before checking for implicit binding.
  1. obj1.myMethod.call( obj2 ); // 3
  2. obj2.myMethod.call( obj1 ); // 2
复制代码
###Hard binding
  This is done with    bind()(ES5).    bind()returns a new function that is hard-coded to call the original function with the    thiscontext set as you specified.  
  1. // Only EC5
  2. myMethod.bind(myObject);
  3. myMethod(); // this === myObject
复制代码
Hard binding takes precedence over explicit binding.
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var obj1 = {
  5.     a: 2
  6. };
  7. var obj2 = {
  8.     a: 3
  9. };
  10. myMethod = myMethod.bind(obj1); // 2
  11. myMethod.call( obj2 ); // 2
复制代码
New binding

  1. function foo(a) {
  2.     this.a = a;
  3. }
  4. var bar = new foo( 2 );
  5. console.log( bar.a ); // 2
复制代码
So    thiswhen the function has been called with new refers to the new instance created.  
  When a function is called with new, it does not care about implicit, explicit, or hard binding, it just creates the new context—which is the new instance.
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };0
复制代码
API calls

  Sometimes, we use a library or a helper object which does something (Ajax, event handling, etc.) and it calls a passed callback. Well, we have to be careful in these cases. Example:
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };1
复制代码
Take a look at the code. You might think that because we are passing “this.onSomethingCoolDone” as a callback, the scope is implicit. That’s wrong, you are passing a reference to that method and not to the way to call it.
  To fix this, there are a few ways:
  
       
  • Usually libraries offer another parameter called scope ( as we do in our library in Pages), so then you can pass the scope you want to get back.  
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };2
复制代码

       
  • You can hard bind the method to the scope you want (ES5).  
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };3
复制代码

       
  • You can create a closure and cache      thisinto      me. For example:  
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };4
复制代码
I do not recommend this approach because it can cause memory leaks and it tends to make you forget about the real scope and rely on variables. You can get to the point where your scope is a real mess.
  This problem applies also to event listeners, timeouts, forEach, etc.
  Understanding “this” is an extensive topic, I recommend the following readings:
  
       
  •       You don’t know js - this & Object prototypes   
  •       code plus article   
  •       toddmotto article  
  ###Related tutorials you might be interested in
我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表