Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. // this
  2.  
  3. var a = {
  4. name: 'Вася',
  5. getName: function () {
  6. return this.name;
  7. },
  8. getContext: function() {
  9. return this;
  10. }
  11. }
  12.  
  13. a.name; // ???
  14. a.getName(); // ???
  15. a.getContext(); // ???
  16.  
  17. // или можем через a.name, но это опасно
  18.  
  19. var a = {
  20. name: 'Вася',
  21. getName: function () {
  22. return a.name;
  23. },
  24. getContext: function() {
  25. return this;
  26. }
  27. };
  28.  
  29. var admin = a;
  30. a = null;
  31.  
  32. admin.sayHi(); // error
  33.  
  34. // Использование this гарантирует, что функция работает именно с тем объектом, в контексте которого вызвана.
  35.  
  36. // ---------------------------------------
  37. // this examples
  38. // ---------------------------------------
  39.  
  40. // 1. Простой вызов function
  41.  
  42. function f() {
  43. console.log(this === window); // true
  44. }
  45. f();
  46.  
  47. // 2. Constructor
  48.  
  49. function f() {
  50. this.x = 5;
  51. console.log(this === window); // false
  52. }
  53.  
  54. var o = new f();
  55. console.log(o.x === 5); // true
  56.  
  57. // 3. Метод obj
  58.  
  59. var o = {
  60. f: function() {
  61. return this;
  62. }
  63. }
  64.  
  65. console.log(o.f() === o); // true
  66.  
  67. // 4. Методы apply, call
  68.  
  69. function f() {
  70. console.log(this.toString()); // 123
  71. }
  72.  
  73. f.call(123); // this внутри функции f будет ссылаться на объект Number со значением 123
  74.  
  75. // 5. bind
  76.  
  77. function f() {
  78. console.log(this.x);
  79. }
  80.  
  81. var bound = f.bind({x: 3}); // bound - новая функция - "обертка", у которой this ссылается на объект {x:3}
  82. bound();// Выведет 3
  83.  
  84. // ---------------------------------------
  85. // Tasks
  86. // ---------------------------------------
  87.  
  88. // 1
  89.  
  90. var f = function() {
  91. this.x = 5;
  92.  
  93. (function() {
  94. this.x = 3;
  95. })();
  96.  
  97. console.log(this.x); //
  98. };
  99.  
  100. new f();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement