“ECMAScript Basics,” introduced the concept that everything is an object, including functions.
ECMA-262 defines an objectas an “unordered collection of properties each of which contains a primitive value,object, or function.” Strictly speaking,this means that an object is an array of values in no particular order.Although this is ECMAScript’s interpretation, an object is more generically defined to be a code-based representation of a noun(person, place, or thing).
Each object is defined by a class, which can be thought of as a recipe for an object. The class defines both the interface of an object (the properties and methods that can be accessed by developers) as well as the inner workings of the object(the code that makes the properties and methods work).The compiler or interpreter uses the class to build objects according to its specifications.
When a program uses a class to create an object,the resulting object is said to be an instance of the class. The only limit to the number of instances that can be created from a single class is the physical memory limitations of the machine on which the code is running.Each instance behaves the same way,but each can handle separate sets of data.The process of creating an object instance from a class is called instantiation.
ECMAScript has no formal classes.Instead,ECMA-262 describes object definitions as the recipes for an object.This is a logical compromise for ECMAScript,because object definitions actually are objects in and of themselves (which I explain shortly).Even though classes don’t actually exist, this book refers to object definitions as classes because the term is more familiar to most developers and, functionally, the two are equivalent.
The object definition is contained within a single function called a constructor.The constructor isn’t a special kind of function; it’s just a regular function that is used to create an object.
Requirements of object-oriented languages
Before a language can be called object-oriented,it must provide four basic capabilities to developers:
- Encapsulation — the capability to store related information,whether data or methods, together in an object
- Aggregation — the capability to store one object inside of another object
- Inheritance — the capability of a class to rely upon another class (or number of classes) for some of its properties and methods
- Polymorphism — the capability to write one function or method that works in a variety of different ways
ECMAScript supports all four of these requirements and so is considered to be object-oriented.
Composition of an object
In ECMAScript, objects are composed of attributes, which are either primitive or reference values.If an attribute contains a function, it is considered to be a method of the object; otherwise, the attribute is considered a property.