Advertisement
Guest User

Untitled

a guest
Apr 21st, 2015
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. ``` javascript
  2.  
  3. function foo() {
  4. console.log(this.a);
  5. }
  6.  
  7. var obj = {
  8. a: 2,
  9. foo: foo
  10. };
  11.  
  12. //function reference/alias
  13. var bar = obj.foo;
  14.  
  15. // ‘a’ is also property on global object
  16. var a = 'oops, global';
  17.  
  18. bar(); // 'oops, global'
  19.  
  20. /* even though bar appears to be a reference to obj.foo, in fact, it's really
  21. just another reference to foo itself. Moreover, the call-site is what matters,
  22. and the call-site is bar(), which is a plain, undecorated call,
  23. and thus the default binding applies. Here's another more subtle example
  24. that uses callbacks: */
  25.  
  26. function foo() {
  27. console.log( this.a );
  28. }
  29.  
  30. function doFoo(fn){
  31. // `fn` is just another reference to `foo`
  32.  
  33. fn(); // <== call-site!
  34. }
  35.  
  36. var obj = {
  37. a: 2,
  38. foo: foo
  39. };
  40.  
  41. // `a` is also a property on the global object
  42. var a = 'oops, global';
  43.  
  44. doFoo( obj.foo ); // 'oops, global'
  45.  
  46. /* Parameter passing is just an implicit assignment, and since we're passing
  47. a function, it's an implicit reference assignment; as in the first example in this
  48. gist, obj.foo just refers to foo and it's executed in the global environment
  49. so THIS refers to the WINDOW */
  50.  
  51. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement