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?