Objects in JavaScript are used to model real-world objects, giving them properties and behavior just like their real-world counterparts. Here's an example using these concepts to create a duck
object:
let duck = {
name: "Aflac",
numLegs: 2
};
let duck = {
name: "Aflac",
numLegs: 2
};
console.log(duck.name);
// This prints "Aflac" to the console
- Objects can have a special type of property, called a method.
- Methods are properties that are functions. This adds different behavior to an object. Here is the
duck
example with a method:
let duck = {
name: "Aflac",
numLegs: 2,
sayName: function() {return "The name of this duck is " + duck.name + ".";}
};
duck.sayName();
// Returns "The name of this duck is Aflac."
-
The last challenge introduced a method to the
duck
object. It usedduck.name
dot notation to access the value for thename
property within the return statement: -
sayName: function() {return "The name of this duck is " + duck.name + ".";}
-
While this is a valid way to access the object's property, there is a pitfall here. If the variable name changes, any code referencing the original name would need to be updated as well. In a short object definition, it isn't a problem, but if an object has many references to its properties there is a greater chance for error.
-
A way to avoid these issues is with the
this
keyword:
let duck = {
name: "Aflac",
numLegs: 2,
sayName: function() {return "The name of this duck is " + this.name + ".";}
};
-
Constructors are functions that create new objects. They define properties and behaviors that will belong to the new object. Think of them as a blueprint for the creation of new objects.
-
Here is an example of a constructor:
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
}
-
This constructor defines a
Bird
object with propertiesname
,color
, andnumLegs
set to Albert, blue, and 2, respectively. Constructors follow a few conventions:- Constructors are defined with a capitalized name to distinguish them from other functions that are not
constructors
. - Constructors use the keyword
this
to set properties of the object they will create. Inside the constructor,this
refers to the new object it will create. - Constructors define properties and behaviors instead of returning a value as other functions might.
- Constructors are defined with a capitalized name to distinguish them from other functions that are not
- Notice that the
new
operator is used when calling a constructor. - Just like any other object, its properties can be accessed and modified
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
// "this" inside the constructor always refers to the object being created
}
let blueBird = new Bird();
let swan = new Bird();
swan.name = "Carlos";
swan.color = "white";
To more easily create different Bird objects, you can design your Bird constructor to accept parameters:
function Bird(name, color) {
this.name = name;
this.color = color;
this.numLegs = 2;
}
- The constructor is more flexible. It's now possible to define the properties for each Bird at the time it is created, which is one way that JavaScript constructors are so useful.
- They group objects together based on shared characteristics and behavior and define a blueprint that automates their creation.
instanceof
allows you to compare an object to a constructor, returningtrue
orfalse
based on whether or not that object was created with the constructor.- Here's an example:
let Bird = function(name, color) {
this.name = name;
this.color = color;
this.numLegs = 2;
}
let crow = new Bird("Alexis", "black");
crow instanceof Bird; // => true
let canary = {
name: "Mildred",
color: "Yellow",
numLegs: 2
};
canary instanceof Bird; // => false
function Bird(name) {
this.name = name;
this.numLegs = 2;
}
let duck = new Bird("Donald");
let canary = new Bird("Tweety");
name
and numLegs
are called own
properties, because they are defined directly on the instance object.
let ownProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
}
}
console.log(ownProps); // prints [ "name", "numLegs" ]
-
Since
numLegs
will probably have the same value for all instances ofBird
, you essentially have a duplicated variablenumLegs
inside eachBird
instance. -
This may not be an issue when there are only two instances, but imagine if there are millions of instances. That would be a lot of duplicated variables.
-
A better way is to use
Bird’s prototype
. Properties in theprototype
are shared among ALL instances of Bird. Here's how to addnumLegs
to theBird prototype
:
Bird.prototype.numLegs = 2;
- Now all instances of
Bird
have thenumLegs
property.
console.log(duck.numLegs); // prints 2
console.log(canary.numLegs); // prints 2
- Since all instances automatically have the properties on the
prototype
, think of aprototype
as a "recipe" for creating objects. Note that theprototype
forduck
andcanary
is part of theBird
constructor asBird.prototype
. Nearly every object in JavaScript has aprototype
property which is part of the constructor function that created it.
- You have now seen two kinds of properties:
own
properties andprototype
properties. - Here is how you add
duck
'sown
properties to the arrayownProps
andprototype
properties to the arrayprototypeProps
:
function Bird(name) {
this.name = name; //own property
}
Bird.prototype.numLegs = 2; // prototype property
let duck = new Bird("Donald");
let ownProps = [];
let prototypeProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
} else {
prototypeProps.push(property);
}
}
console.log(ownProps); // prints ["name"]
console.log(prototypeProps); // prints ["numLegs"]
- There is a special
constructor
property located on the object instancesduck
andbeagle
that were created in the previous challenges:
let duck = new Bird();
let beagle = new Dog();
console.log(duck.constructor === Bird); //prints true
console.log(beagle.constructor === Dog); //prints true
- Note that the
constructor
property is a reference to the constructor function that created the instance. The advantage of theconstructor
property is that it's possible to check for this property to find out what kind of object it is. Here's an example of how this could be used:
function joinBirdFraternity(candidate) {
if (candidate.constructor === Bird) {
return true;
} else {
return false;
}
}
- Since the
constructor
property can be overwritten it’s generally better to use theinstanceof
method to check the type of an object.
- This becomes tedious after more than a few properties.
Bird.prototype.eat = function() {
console.log("nom nom nom");
}
Bird.prototype.describe = function() {
console.log("My name is " + this.name);
}
- A more efficient way is to set the
prototype
to a new object that already contains the properties. This way, the properties are added all at once:
Bird.prototype = {
numLegs: 2,
eat: function() {
console.log("nom nom nom");
},
describe: function() {
console.log("My name is " + this.name);
}
};
- There is one crucial side effect of manually setting the prototype to a new object. It erases the
constructor
property! - This property can be used to check which constructor function created the instance, but since the property has been overwritten, it now gives false results:
duck.constructor === Bird; // false -- Oops
duck.constructor === Object; // true, all objects inherit from Object.prototype
duck instanceof Bird; // true, still works
- To fix this, whenever a prototype is manually set to a new object, remember to define the
constructor
property:
Bird.prototype = {
constructor: Bird, // define the constructor property
numLegs: 2,
eat: function() {
console.log("nom nom nom");
},
describe: function() {
console.log("My name is " + this.name);
}
};
- Just like people inherit genes from their parents, an object inherits its
prototype
directly from the constructor function that created it. For example, here theBird
constructor creates theduck
object:
function Bird(name) {
this.name = name;
}
let duck = new Bird("Donald");
Bird.prototype.isPrototypeOf(duck);
// returns true
- All objects in JavaScript (with a few exceptions) have a
prototype
. Also, an object’sprototype
itself is an object.
function Bird(name) {
this.name = name;
}
typeof Bird.prototype; // yields 'object'
- Because a
prototype
is an object, aprototype
can have its ownprototype
! In this case, theprototype
ofBird.prototype
isObject.prototype
:
Object.prototype.isPrototypeOf(Bird.prototype); // returns true
- How is this useful? You may recall the
hasOwnProperty
method from a previous challenge:
let duck = new Bird("Donald");
duck.hasOwnProperty("name"); // yields true
- The
hasOwnProperty
method is defined inObject.prototype
, which can be accessed byBird.prototype
, which can then be accessed byduck
. This is an example of theprototype
chain. In thisprototype
chain,Bird
is thesupertype
forduck
, whileduck
is thesubtype
.Object
is asupertype
for bothBird
andduck
.Object
is asupertype
for all objects in JavaScript. Therefore, any object can use thehasOwnProperty
method.
-
There's a principle in programming called Don't Repeat Yourself (DRY). The reason repeated code is a problem is because any change requires fixing code in multiple places. This usually means more work for programmers and more room for errors.
-
Notice in the example below that the
describe
method is shared byBird
andDog
:
Bird.prototype = {
constructor: Bird,
describe: function() {
console.log("My name is " + this.name);
}
};
Dog.prototype = {
constructor: Dog,
describe: function() {
console.log("My name is " + this.name);
}
};
- The
describe
method is repeated in two places. The code can be edited to follow the DRY principle by creating asupertype
(or parent) calledAnimal
:
function Animal() { };
Animal.prototype = {
constructor: Animal,
describe: function() {
console.log("My name is " + this.name);
}
};
- Since
Animal
includes thedescribe
method, you can remove it fromBird
andDog
:
Bird.prototype = {
constructor: Bird
};
Dog.prototype = {
constructor: Dog
};
- You already know one way to create an instance of Animal using the new operator:
let animal = new Animal();
- There are some disadvantages when using this syntax for inheritance, which are too complex for the scope of this challenge. Instead, here's an alternative approach without those disadvantages:
let animal = Object.create(Animal.prototype);
Object.create(obj)
creates a new object, and setsobj
as the new object'sprototype
. Recall that theprototype
is like the "recipe" for creating an object. By setting theprototype
ofanimal
to beAnimal's prototype
, you are effectively giving theanimal
instance the same "recipe" as any other instance ofAnimal
.
animal.eat(); // prints "nom nom nom"
animal instanceof Animal; // => true
- This challenge covers the next step: set the
prototype
of the subtype (or child)—in this case,Bird
—to be an instance ofAnimal
. - Remember that the
prototype
is like the "recipe" for creating an object. In a way, the recipe forBird
now includes all the key "ingredients" fromAnimal
.
Bird.prototype = Object.create(Animal.prototype);
let duck = new Bird("Donald");
duck.eat(); // prints "nom nom nom"
- When an object inherits its
prototype
from another object, it also inherits the supertype's constructor property. - Here's an example:
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
let duck = new Bird();
duck.constructor // function Animal(){...}
- But
duck
and all instances ofBird
should show that they were constructed byBird
and notAnimal
. To do so, you can manually setBird's
constructor property to theBird
object:
Bird.prototype.constructor = Bird;
duck.constructor // function Bird(){...}
- A constructor function that inherits its
prototype
object from a supertype constructor function can still have its own methods in addition to inherited methods. - For example,
Bird
is a constructor that inherits itsprototype
fromAnimal
:
function Animal() { }
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
- In addition to what is inherited from
Animal
, you want to add behavior that is unique toBird
objects. Here, Bird will get afly()
function. Functions are added toBird's
prototype
the same way as any constructor function:
Bird.prototype.fly = function() {
console.log("I'm flying!");
};
let duck = new Bird();
duck.eat(); // prints "nom nom nom"
duck.fly(); // prints "I'm flying!"
- In previous lessons, you learned that an object can inherit its behavior (methods) from another object by referencing its
prototype
object:
ChildObject.prototype = Object.create(ParentObject.prototype);
- Then the
ChildObject
received its own methods by chaining them onto itsprototype
:
ChildObject.prototype.methodName = function() {...};
- It's possible to override an inherited method. It's done the same way - by adding a method to
ChildObject.prototype
using the same method name as the one to override. Here's an example ofBird
overriding theeat()
method inherited fromAnimal
:
function Animal() { }
Animal.prototype.eat = function() {
return "nom nom nom";
};
function Bird() { }
// Inherit all methods from Animal
Bird.prototype = Object.create(Animal.prototype);
// Bird.eat() overrides Animal.eat()
Bird.prototype.eat = function() {
return "peck peck peck";
};
-
If you have an instance
let duck = new Bird()
; and you callduck.eat()
, this is how JavaScript looks for the method onduck’s prototype
chain:- duck => Is eat() defined here? No.
- Bird => Is eat() defined here? => Yes. Execute it and stop searching.
- Animal => eat() is also defined, but JavaScript stopped searching before reaching this level.
- Object => JavaScript stopped searching before reaching this level.
-
As you have seen, behavior is shared through inheritance. However, there are cases when inheritance is not the best solution. Inheritance does not work well for unrelated objects like
Bird
andAirplane
. They can both fly, but aBird
is not a type ofAirplane
and vice versa. -
For unrelated objects, it's better to use mixins. A mixin allows other objects to use a collection of functions.
-
The
flyMixin
takes any object and gives it thefly
method. -
Note how the mixin allows for the same
fly
method to be reused by unrelated objectsbird
andplane
.
let flyMixin = function(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
}
};
let bird = {
name: "Donald",
numLegs: 2
};
let plane = {
model: "777",
numPassengers: 524
};
flyMixin(bird);
flyMixin(plane);
bird.fly(); // prints "Flying, wooosh!"
plane.fly(); // prints "Flying, wooosh!"
Object Oriented Programming: Use Closure to Protect Properties Within an Object from Being Modified Externally
- In the previous challenge,
bird
had a public propertyname
. It is considered public because it can be accessed and changed outside ofbird
's definition.
bird.name = "Duffy";
- Therefore, any part of your code can easily change the name of
bird
to any value. Think about things like passwords and bank accounts being easily changeable by any part of your codebase. That could cause a lot of issues. - The simplest way to make this public property private is by creating a variable within the constructor function. This changes the scope of that variable to be within the constructor function versus available globally. This way, the variable can only be accessed and changed by methods also within the constructor function.
function Bird() {
let hatchedEgg = 10; // private variable
/* publicly available method that a bird object can use */
this.getHatchedEggCount = function() {
return hatchedEgg;
};
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // returns 10
- Here
getHatchedEggCount
is a privileged method, because it has access to the private variablehatchedEgg
. This is possible becausehatchedEgg
is declared in the same context asgetHatchedEggCount
. In JavaScript, a function always has access to the context in which it was created. This is calledclosure
.
- A common pattern in JavaScript is to execute a function as soon as it is declared:
- Note that the function has no name and is not stored in a variable. The two parentheses () at the end of the function expression cause it to be immediately executed or invoked. This pattern is known as an immediately invoked function expression or IIFE.
(function () {
console.log("Chirp, chirp!");
})(); // this is an anonymous function expression that executes right away
// Outputs "Chirp, chirp!" immediately
- An immediately invoked function expression (IIFE) is often used to group related functionality into a single object or module. For example, an earlier challenge defined two mixins:
function glideMixin(obj) {
obj.glide = function() {
console.log("Gliding on the water");
};
}
function flyMixin(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
};
}
- We can group these mixins into a module as follows:
let motionModule = (function () {
return {
glideMixin: function(obj) {
obj.glide = function() {
console.log("Gliding on the water");
};
},
flyMixin: function(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
};
}
}
})(); // The two parentheses cause the function to be immediately invoked
- Note that you have an immediately invoked function expression (IIFE) that returns an object
motionModule
. This returned object contains all of the mixin behaviors as properties of the object. The advantage of the module pattern is that all of the motion behaviors can be packaged into a single object that can then be used by other parts of your code. Here is an example using it:
motionModule.glideMixin(duck);
duck.glide();