Javascript : OOP Basics

Original Source from Mozilla Developer Network

function makePerson(first, last) {
    return {
        first: first,
        last: last,
        fullName: function() {
            return this.first + ' ' + this.last;
        },
        fullNameReversed: function() {
            return this.last + ', ' + this.first;
        }
    }
}

3WT?
Everytime we create a Person it creates two brand new function objects.

function personFullName() {
	return this.first + ' ' + this.last;
}

function personFullNameReversed() {
	return this.last + ', ' + this.first;
}

function Person(first, last) {
	this.first = first;
	this.last = last;
	this.fullName = personFullName;
	this.fullNameReversed = personFullNameReversed;
}

WCWT?
Function code is shared.

function Person(first, last) {
	this.first = first;
	this.last = last;
}
Person.prototype.fullName = function() {
	return this.first + ' ' + this.last;
}
Person.prototype.personFullNameReversed = function() {
	return this.last + ', ' + this.first;
}

WCWT?
We can add extra methods to an existing object at runtime.

Example : Adding a function at runtime.

Person.prototype.firstNameCaps = function() {
    return this.first.toUpperCase()
}

Another Example : Changing prototype.toString function

Person.prototype.toString = function() {
   return '<Person: ' + this.fullName() + '>';
}
var s = new Person("Sim", "Son");

If we print s

[object Object] – Without our new toString()
<Person: Simon Willison> – With our new toString()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: