JavaScript is partly an object-oriented language.
To learn JavaScript, we got to learn the object-oriented parts of JavaScript.
In this article, we’ll look at constructors and object shorthands.
The constructor Property
The constructor
property is part of an instance object.
It contains the reference to the constructor function.
So if we have:
function Person(name, occupation) {
this.name = name;
this.occupation = occupation;
this.whoAreYou = function() {
return `${this.name} ${this.occupation}`
};
}
const jane = new Person('jane', 'writer');
Then:
jane.constructor
is the Person
constructor function.
The instanceof Operator
The instanceof
operator lets us check whether the object is created with the given constructor.
For instance, we can write:
jane instanceof Person
then we get true
.
And if we write:
jane instanceof Object
and that’s also true
.
Functions that Return Objects
A function that returns an object is called a factory function.
For instance, we can create a factory function by writing:
function factory(name) {
return {
name
};
}
Then we can call it by writing:
const james = factory('james');
Then we get james.names
is 'james'
.
Constructors can also be written to return an object instead of return an instance of this
.
For instance, we can write:
function C() {
this.a = 1;
return {
b: 2
};
}
Then if we invoke the construction:
const c = new C()
and then we get:
{b: 2}
Passing Objects
We can pass objects into a function.
For instance, we can write:
const reset = function(o) {
o.count = 0;
};
Then we can use it by writing:
const obj = {
count: 100
}
reset(obj);
console.log(obj);
And we get:
{count: 0}
from the console log.
Comparing Objects
We can’t compare objects with ===
since it only returns true
if they have the same reference.
For instance, if we have:
const james = {
breed: 'cat'
};
const mary = {
breed: 'cat'
};
Then:
james === mary
returns false
even if they have exactly the same properties.
The only way that it can return true
is if we assign one to object to the other.
For instance, we write:
const james = {
breed: 'cat'
};
const mary = james;
Then:
james === mary
returns true
.
ES6 Object Literals
ES6 gives us a much shorter syntax for defining object literals.
For instance, if we have:
let foo = 1
let bar = 2
let obj = {
foo: foo,
bar: bar
}
Then we can shorten that to:
let foo = 1
let bar = 2
let obj = {
foo,
bar
}
We can also shorten methods.
For instance, instead of writing:
const obj = {
prop: 1,
modifier: function() {
console.log(this.prop);
}
}
We write:
const obj = {
prop: 1,
modifier() {
console.log(this.prop);
}
}
We can also use computed property keys.
For instance, we can write:
let vehicle = "car";
let car = {
[`${vehicle}_model`]: "toyota"
}
We can do the same for methods.
Conclusion
Object literals can be written in various ways JavaScript.
We can check the constructor with the constructor
property and instanceof
.