OOP in JavaScript
- Let's start by looking at how you could define a person with a normal function. Add this function within the
script
element:function createNewPerson(name) { var obj = {}; obj.name = name; obj.greeting = function() { alert('Hi! I\'m ' + obj.name + '.'); }; return obj; }
- You can now create a new person by calling this function — try the following lines in your browser's JavaScript console:
var salva = createNewPerson('Salva'); salva.name; salva.greeting();
- This works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and return it? Fortunately, JavaScript provides us with a handy shortcut, in the form of constructor functions — let's make one now!
- Replace your previous function with the following:
function Person(name) { this.name = name; this.greeting = function() { alert('Hi! I\'m ' + this.name + '.'); }; }
- Add the following lines below your previous code addition:
var person1 = new Person('Bob'); var person2 = new Person('Sarah');
- Save your code and reload it in the browser, and try entering the following lines into your JS console:
person1.name person1.greeting() person2.name person2.greeting()
- Remove the code you inserted so far, and add in this replacement constructor — this is exactly the same as the simple example in principle, with just a bit more complexity:
function Person(first, last, age, gender, interests) { this.name = { 'first': first, 'last' : last }; this.age = age; this.gender = gender; this.interests = interests; this.bio = function() { alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.'); }; this.greeting = function() { alert('Hi! I\'m ' + this.name.first + '.'); }; }
- Now add in the following line below it, to create an object instance from it:
var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
The constructor function is JavaScript's version of a class. You'll notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and methods. You'll see the
this
keyword being used here as well — it is basically saying that whenever one of these object instances is created, the object's name
property will be equal to the name value passed to the constructor call, and the greeting()
method will use the name value passed to the constructor call too.
So how do we call a constructor to create some objects?
Cool!
Creating our finished constructor
The example we looked at above was only a simple example to get us started. Let's now get on and create our final
Person()
constructor function.
You'll now see that you can access the properties and methods just like we did previously — try these in your JS console:
person1['age']
person1.interests[1]
person1.bio()
// etc.
The Object() constructor
First of all, you can use the
Object()
constructor to create a new object. Yes, even generic objects have a constructor, which generates an empty object.- Try entering this into your browser's JavaScript console:
var person1 = new Object();
- This stores an empty object in the
person1
variable. You can then add properties and methods to this object using dot or bracket notation as desired; try these examples in your console:person1.name = 'Chris'; person1['age'] = 38; person1.greeting = function() { alert('Hi! I\'m ' + this.name + '.'); };
- You can also pass an object literal to the
Object()
constructor as a parameter, to prefill it with properties/methods. Try this in your JS console:var person1 = new Object({ name: 'Chris', age: 38, greeting: function() { alert('Hi! I\'m ' + this.name + '.'); } });
Using the create() method
Constructors can help you give your code order—you can create constructors in one place, then create instances as needed, and it is clear where they came from.
However, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. JavaScript has a built-in method called
create()
that allows you to do that. With it, you can create a new object based on any existing object.- With your finished exercise from the previous sections loaded in the browser, try this in your JavaScript console:
var person2 = Object.create(person1);
- Now try these:
person2.name person2.greeting()
You'll see that
person2
has been created based on person1
—it has the same properties and method available to it.
One limitation of
create()
is that IE8 does not support it. So constructors may be more effective if you want to support older browsers.