1

I was trying to learn OO techniques in javascript. Most of the web sites use prototype inheritance.

But, I am trying to understand why the following is bad (and still can achieve what prototype inheritance can do):

        //create parent class
    var Person = function (vId, vName) {
        this.Id = vId;
        this.Name = vName;

        this.Display = function () {
            alert("Id=" + this.Id);
        }
    };

    //create new class
    var Emp = function (vId, vName, vOfficeMail) {
        Person.call(this, vId, vName)
        this.OfficeEmail = vOfficeMail;

        this.Display = function () {
            alert("Id=" + this.Id + ", OfficeMail=" + this.OfficeEmail);
        }
    };

    //create instance of child class
    var oEmp = new Emp(1001, "Scott", "[email protected]"); //using Child's constructor
    //call display method in child class
    oEmp.Display();

    //create instance of parent class
    var oPerson = new Person(1002, "Smith"); //using Parent's constructor
    //call display method in parent class
    oPerson.Display();
1
  • 2
    Prototype inheritance is the only inheritance JavaScript knows. Commented Jul 8, 2012 at 20:21

2 Answers 2

4

This is what I think is the most important, and a simple explanation.

This code will create the function once for each object:

this.Display = function () {
    alert("Id=" + this.Id);
}

Using prototypes, the function is instead created only once and applied to all objects of that kind. Wastes less memory and less CPU-power.

This code will show what I'm talking about:

var Person = function (vId, vName) {
        this.Id = vId;
        this.Name = vName;

        this.Display = function () {
            alert("Id=" + this.Id);
        }
    };

    var a = new Person(1, 2);
    var b = new Person(3, 4);

    var instanceEqual = (a.Display == b.Display);// false
    alert("Instance functions equal: " + instanceEqual);

    Person.prototype.Display2 = function () {
            alert("Id=" + this.Id);
        }

    var prototypeEqual = (a.Display2 == b.Display2);// true
    alert("Prototype functions equal: " + prototypeEqual);

Jsfiddle: http://jsfiddle.net/nPnrk/

Sign up to request clarification or add additional context in comments.

Comments

2

The prototype object allows you to keep behaviors shared by many object instances all in one place. From there, they can be changed or extended dynamically if need be, with the effect being to immediately alter the capabilities of all constructed objects inheriting from the prototype.

There are other nice things too, but to me that's the most significant thing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.