Class pointing problems in JavaScript

Considerations for using classes:

  1. Classes do not have variable promotion in ES6, so you must define a class before you can instantiate an object from it
  2. Class attributes and methods must use this instead of the name of the property
class Start {
  constructor(uname, age) {
    this.uname = uname;
    this.age = age;
  }
  sing() {
    console.log(this.uname); }}Copy the code

If we want to call sing() directly when creating an object, we can take advantage of constructor’s ability to call sing() directly from within the constructor. Since the sing() method is inside a class and cannot point directly to an instance, we need to add this

class Start {
  constructor(uname, age) {
    this.uname = uname;
    this.age = age;
    this.sing();
  }
  sing() {
    console.log(this.uname); }}var ldh = new Start("Andy Lau".50); / / Andy lau
Copy the code

Class this refers to the problem.

  1. This in constructor points to the instance object, and this in a method points to the caller of the method
<button>click me</button>
<script>
  class Start {
    constructor(uname, age) {
      this.uname = uname;
      this.age = age;
      this.btn = document.querySelector("button");
      this.btn.onclick = this.sing;
    }
    sing() {
      console.log(this.uname); / / undefined; Because this refers to a button, and there is no uname in a button}}var ldh = new Start("Andy Lau".50);
  ldh.sing(); // Andy Lau; Because this refers to whoever calls this method, we can get uname
</script>
Copy the code
  1. But if we need to print out the class properties by clicking button in the method, we can set a global variable:
<button>click me</button>
<script>
  var that = null;
  class Start {
    constructor(uname, age) {
      that = this;
      this.uname = uname;
      this.age = age;
      this.btn = document.querySelector("button");
      this.btn.onclick = this.sing;
    }
    sing() {
      console.log(that.uname); // Click button to print out uname
      console.log(this.uname); }}var ldh = new Start("Andy Lau".50);
  ldh.sing(); // Andy Lau; Because this refers to whoever calls this method, we can get uname
</script>
Copy the code