DEV Community

Susan Wangari
Susan Wangari

Posted on

Diving into Object Oriented Programming

Just like the title,Object Oriented Programming is all about objects.Objects have properties and these are what makes an object.One thing to note is that objects can share properties but have different values for those properties.

Properties in an object can be accessed in 2 ways:

-using dot notation

for example

let duck = {
name: "Aflac",
numLegs: 2
};
console.log(duck.name);

-using bracket notation

for example

let duck = {
name: "Aflac",
numLegs: 2
};
console.log(duck[name]);

Objects have constructors.Constructors are functions that create new objects.They use this keyword to set properties of the object they will create.They are defined with a capitalized name to distinguish them from other functions that are not constructors.Objects properties created with constructors are separated with a semicolon unlike other object properties which are separated with a comma.new operator is used when calling a constructor.

for example:

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();
When a constructor function creates a new object,it is an instance of its constructor.instance of allows you to compare an object to a constructor.It returns true if the constructor created the object and false if the constructor did not create the object.

for 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
prototype properties reduce code duplication.They are shared among all instances of an object.

for example:

Bird.prototype.numLegs = 2;
console.log(duck.numLegs); // prints 2
console.log(canary.numLegs); // prints 2
Using Bird.prototype ensures that you do not have to define numLegs is not defined in both duck and canary.

Objects have methods.One of these methods is Object.create().

for example:

let animal = Object.create(Animal.prototype);

Top comments (0)