Constructors as Functions

Reading Professional JavaScript for Web Developers, in Chapter 6, the author was talking about the downside of Constructors is that methods are created once for each instance. So, person1 and person2 have a method called sayName(), but those methods are not the same instance of Function. So every time a function is defined, it’s actually an object being instantiated. Logically, the constructor actually looks like this:

function Personc(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = new Function(“alert(this.name)”);
}

The mechanics of creating a new instance of Function remain the same. Thus,

alert(person1.sayName == person2.sayName); //false   (p.183)

It’s possible to work around this limitation by moving the function definition outside of the constructor,

function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = sayName;
}

function sayName() {
alert(this.name);
}

**** Inside the constructor, the sayName property is set equal to the global sayName() function, since the sayName property now contains just a pointer to a function, both person1 and person2 end up sharing the sayName() function that is defined in the global scope. This solves the problem of having duplicate functions that do the same thing but also creates some clutter in the global scope by introducing a function that can realistically be used only in relation to an object. (p.184)

Reflection

Imagine that you are creating thousands of instances of Person, it saves you thousands of “instances” in your program.

The Prototype Pattern actually wipe out the downside of the Constructor Pattern.

For example,

function Person() {

}
Person.prototype.name = name;
Person.prototype.age = age;
Person.prototype.job = job;
Person.prototype.sayName = function() {
alert(this.name);
};

person1 and person2 are both accessing the same set of properties and the sameName () function.

Advertisements

3 thoughts on “Constructors as Functions”

  1. Hi Yumiko, great blog you have here, keep it up! If you need help with project 3, feel free to email me at sheryl.v.lun at gmail dot com, it’s easier than communicating through github.

    Cheers!

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