For functions, 'this' is bound differently, but for variables, I cannot figure out if there is a difference.
class Widget {
constructor(constructorName) {
this.constructorName = constructorName;
}
nonConstructorName = "nonConstructorName1";
}
var myWidget = new Widget("myConstructorName1");
console.log(myWidget.constructorName); // "myConstructorName1"
console.log(myWidget.nonConstructorName); // "nonConstructorName1"
myWidget.constructorName = "myConstructorName2";
myWidget.nonConstructorName = "nonConstructorName2";
console.log(myWidget.constructorName); // "myConstructorName2"
console.log(myWidget.nonConstructorName); // "nonConstructorName2"
console.log(myWidget.prototype.constructorName); // "undefined"
console.log(myWidget.prototype.nonConstructorName); // "undefined"
console.log(myWidget.__proto__.constructorName); // "undefined"
console.log(myWidget.__proto__.nonConstructorName); // "undefined"
var myNewWidget = new Widget("myConstructorName3");
console.log(myNewWidget.nonConstructorName); // "nonConstructorName1"
Classes create objects through the new operator. Each object has some properties (data or method) added by the class. The class stores some properties (data or method) itself, which are usually used to interact with instances.
A class definition can only include constructors and functions. These components are together called as the data members of a class. The classes contain constructors that allocates the memory to the objects of a class.
Definition and UsageThe constructor() method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method. Note: A class cannot have more than one constructor() method.
Public static methodsThe static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.
Answer in comments by @merianos-nikos...
"The approach here is to use the scope of the constructor function, which is private, to store private data. For methods to have access to this private data they must be created within the constructor as well, meaning you're recreating them with every instance. This is a performance and memory penalty, but some believe the penalty is acceptable."
Private properties in JavaScript ES6 classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With