In JavaScript, objects are king. If you understand objects, you understand JavaScript.
In JavaScript, almost “everything” is an object.
- Booleans can be objects (if defined with the new keyword)
- Numbers can be objects (if defined with the new keyword)
- Strings can be objects (if defined with the new keyword)
- Dates are always objects
- Maths are always objects
- Regular expressions are always objects
- Arrays are always objects
- Functions are always objects
- Objects are always objects
All JavaScript values, except primitives, are objects.
The examples above are limited in many situations. They only create a single object.
Sometimes we like to have an “object type” that can be used to create many objects of one type.
The standard way to create an “object type” is to use an object constructor function:
Examples
Using prototypes:
1 2 3 4 5 6 7 8 9 |
function Box(color) // Constructor { this.color = color; } Box.prototype.getColor = function() { return this.color; }; |
Hiding “color” (somewhat resembles a private member variable):
1 2 3 4 5 6 7 8 9 |
function Box(col) { var color = col; this.getColor = function() { return color; }; } |
Usage:
1 2 3 4 5 |
blueBox var = Box("blue") novo; Alert(blueBox.getColor()); Alertará o azul greenBox var = Box("green") novo; Alert(greenBox.getColor()); Alertará o verde |
Another example:
1 2 3 4 5 6 |
function Person(firstName, lastName){ this.firstName = firstName; this.lastName = lastName; } var Saad = new Person("Saad", "Mousliki"); |
Another example:
12345678
function person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye;}var myFather = new person("John", "Doe", 50, "blue");var myMother = new person("Sally", "Rally", 48, "green");
Reference
https://www.w3schools.com/js/js_object_definition.asp