Instance Variables in Javascript Classes

I mainly code PHP and Java, but sometimes I will work on the project interface and use JavaScript. I usually create objects differently than below, but I stumbled upon this, and I was curious that the syntax is similar to what I usually program.

I stomped trying to figure out how to use instance variables in JavaScript classes using the syntax below. I tried to declare instance variables name;, or _name;, or var name;, or all of these previous variables and add = null;, but still get errors in my console. Mistakes are mostly my-file.js:2 Uncaught SyntaxError: Unexpected identifier. I'm just trying to set my instance variable through my constructor.

How to use instance variables in JavaScript using the syntax below?

class MyClass {
  var _name;

  constructor(name) {
    _name = name;
    alert("Hello world, from OO JS!");
    this.myFunction();
  }

  myFunction() {
    document.getElementById("myElement").addEventListener("click", function() {
        console.log("Ant function runs. Hello!");
    });
  }
}

window.onload = function() {
  var person = "John Smith";
  var myClass = new MyClass(person);
}
+4
2

proposal, :

class A {
   property = "value";
}

BTW, (.. ), this.property:

class A {
    property = "value";

    constructor() {
        console.log(this.property);
    }
}

, , Babel.

+6

; this._name = name.

@Ryan ? this._name undefined.

* this; . var that = this; that:

myFunction() {
  var that = this;

  document.getElementById("myElement").addEventListener("click", function() {
    console.log(that._name);
  });
}

, this Function.prototype.bind:

myFunction() {
  document.getElementById("myElement").addEventListener("click", function() {
    console.log(this._name);
  }.bind(this));
}

ES6s, this, ( this):

myFunction() {
  document.getElementById("myElement").addEventListener("click", () => {
    console.log(this._name);
  });
}
+4

Source: https://habr.com/ru/post/1661073/


All Articles