Guest User

Untitled

a guest
Jun 20th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. # THIS
  2.  
  3. To understand this binding, we have to understand the call-site: the location in code where a function is called (not where it's declared). We must inspect the call-site to answer the question: what's this this a reference to?
  4.  
  5. ### default binding
  6. The first rule we will examine comes from the most common case of function calls: standalone function invocation. Think of this this rule as the default catch-all rule when none of the other rules apply.
  7. ```javascript
  8. function foo() {
  9. console.log( this.a );
  10. }
  11.  
  12. var a = 2;
  13.  
  14. foo(); // 2
  15. ```
  16.  
  17. ### implicit binding
  18. Another rule to consider is: does the call-site have a context object, also referred to as an owning or containing object, though these alternate terms could be slightly misleading.
  19. ```javascript
  20. function foo() {
  21. console.log( this.a );
  22. }
  23.  
  24. var obj = {
  25. a: 2,
  26. foo: foo
  27. };
  28.  
  29. obj.foo(); // 2
  30. ```
  31.  
  32. ### Implicitly Lost
  33. If you take the function out of context by passing its reference, it'll lose reference to this, or will switch back to default binding.
  34. ```javascript
  35. function foo() {
  36. console.log( this.a );
  37. }
  38.  
  39. var obj = {
  40. a: 2,
  41. foo: foo
  42. };
  43.  
  44. var bar = obj.foo; // function reference/alias!
  45.  
  46. var a = "oops, global"; // `a` also property on global object
  47.  
  48. bar(); // "oops, global"
  49. ```
  50.  
  51. ### Explicit binding
  52. Invoking foo with explicit binding by foo.call(..) allows us to force its this to be obj.
  53. ```javascript
  54. function foo() {
  55. console.log( this.a );
  56. }
  57.  
  58. var obj = {
  59. a: 2
  60. };
  61.  
  62. foo.call( obj ); // 2
  63. ```
  64.  
  65. ### new keyword Binding
  66. By calling foo(..) with new in front of it, we've constructed a new object and set that new object as the this for the call of foo(..). So new is the final way that a function call's this can be bound.
  67. ```javascript
  68. function foo(a) {
  69. this.a = a;
  70. }
  71.  
  72. var bar = new foo( 2 );
  73. console.log( bar.a ); // 2
  74. ```
  75.  
  76. ### ES6 Arrow functions
  77. Instead of using the four standard this rules, arrow-functions adopt the this binding from the enclosing (function or global) scope.
  78. ```javascript
  79. function foo() {
  80. setTimeout(() => {
  81. // `this` here is lexically adopted from `foo()`
  82. console.log( this.a );
  83. },100);
  84. }
  85.  
  86. var obj = {
  87. a: 2
  88. };
  89.  
  90. foo.call( obj ); // 2
  91. ```
Add Comment
Please, Sign In to add comment