Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function() {
  2.     this.a = "a"; // This obc creates a variable called "a" in this function, like a field.
  3. }
  4.  
  5. class A {
  6.  
  7.     test() {
  8.         this.a = "a2"; // Same here. The "a" variable in the other function is not the same as this one. But...
  9.     }
  10. }
  11.  
  12. class B {
  13.  
  14.     test() {
  15.         this.a = function() {
  16.             this.a = "a3"; // HOLD UP! the "this" identifier IS NOT referencing the class. It is referencing the function, like how i showed it in the first example!!!!!
  17.         }; // "a" is now a function. you can call it if you want.
  18.         this.a();
  19.     }
  20.  
  21.     test2() { // If you want to fix that problem you need to do this:
  22.        
  23.         this.a = function() {
  24.             this.a = "a3";
  25.         }.bind(this); // This bind function can be used for a ton of things, but you are passing in an instance of "this" that you want to use. You can also do stuff like:
  26.  
  27.         this.b = function(myName) {
  28.             console.log(myName); // "doggo"
  29.         }.bind(this, "doggo");
  30.  
  31.         // If you aren't really referencing "this", you can just pass in null as the first parameter
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement