A problem of this in class

recently, in class, the first code is as follows:

class Logger {
  printName(name = "there") {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
const { printName } = logger; 
printName(); // TypeError: Cannot read property "print" of undefined

when instantiated, this points to the instantiated object, so after printName () runs this method, because this points to logger, there is no print method in logger (the print method is in the prototype).
but here"s the problem. I changed the last line of the above code to this:

logger.printName();

this is not wrong, and it can be displayed correctly.
what is the difference between printName () and logger.printName (), and why does the latter correctly show that the this points in, printName () are not all instantiated logger?

Jun.28,2021

first of all, you know that the essence of class is actually the prototype chain prototype
, then the above code is essentially:

< hr >
function Logger () {

}

Logger.prototype.printName = function(name = 'there') {  
  this.print(`Hello ${name}`);
};  

Logger.prototype.print = function(text) {  
  console.log(text);
};  

const logger = new Logger();
logger.printName();

you can see that the method printName method is on the prototype chain, and this points to the function Logger (), which points to the entity after materialization.
the this point here is a new object!

< hr >

and what you say here

const { printName } = logger; 

this is the deconstruction of the object, which applies to this type of:

let logger = {
    printName: function () {
        .....////
    }
}

and the this here points to the different construction methods, properties and this directions of the above two window,. It is unreasonable for you to deconstruct the prototype chain of the new object directly with the deconstruction of es6.


js this is generated when is run (except for arrow functions or this is generated at definition)
a.printName () printName this is a
printName () this is window <

if you want to use it this way, please refer to vuex Code

.
  

directly call to become a global function this points to window

Menu