Classes
- A class defines a common structure for many objects. The structure is made up of properties, constructors, and methods.
- An object is a single instance of a class whose data lives somewhere in memory distinct from all other objects.
Properties
- An object’s state is stored in its properties and each object has its own set of properties.
Constructors
- Constructors are invoked to create objects that are instances of a class. They are written like methods but with the special name
contructor
.
- Constructor are invoked using the keyword
new
followed by the class name and an argument list that corresponds to one of the class’s constructors.
- The job of a constructor is to initialize the state of an object and leave it in a usable state. Often constructors assign the values passed as arguments to the constructor to the object’s properties.
- Constructors have parameter lists that work just like method parameter lists, defining local variables that are initialized with the values of the arguments passed to a call to the constructor. The arguments should provide the data needed to initialize the object’s state.
- If a class doesn’t contain an explicit constructor, Javascript provides a default constructor that does nothing.
Methods in classes
- An object’s behavior—what we can do with the object—is defined by the methods in its class.
- Methods are a special kind of function that have access to a special variable
this
which is the value of the object on which the method was invoked.
- Methods can use
this
to access the object’s properties and to invoke other methods defined in the class.
Invoking methods
- Methods are always invoked on some object, typically via the dot operator, e.g.
obj.someMethod()
.
- Within a class, we use
this
to refer to the current object in order to invoke other methods on it, e.g. this.doWhatever()
.
- Instance methods in other classes are invoked on a particular object using an expression that evaluates to a reference to the object, the dot operator, and the name of the method, e.g.
s.slice(1)
to invoke the substring
method on a string instance referenced by the variable s
.