javascript Prototype

prototype

by deshpandeakhil

HTML

<div id="results" />

CSS

body {
    margin:10px;
}
.pass {
    color:green;
}
.fail {
    color:red;
    text-decoration:line-through;
}

JavaScript

function assert(value, desc) {
    var res = $("#results");
    var li = document.createElement("li");
    li.className = value ? "pass" : "fail";
    li.appendChild(document.createTextNode(desc));
    res.append(li);
}

// functions have prototype property which initially is set to an empty object
// it doesnt serve much purpose until the function is used as a constructor
function Person() {};
Person.prototype.goToWork = function () {
    return true;
};

var person1 = Person();
assert(person1 === undefined, "person1 is undefined");

var person2 = new Person();
assert(person2 && person2.goToWork && person2.goToWork(), "person2 is a object with goToWork");

// each object in javascript has a implicit property named constructor that references the constructor that was used to create the object. prototype then is the property of constructor therefore each object has a way to find its prototype
assert(true, person2.constructor);
assert(true, person2.constructor.prototype.goToWork);
assert(person2.constructor.prototype.goToWork(), "accessing prototype from instance");
assert(person2.constructor === Person, "constructor can be accessed via the constructor property");
assert(person2.constructor.prototype.goToWork === person2.goToWork, "both references are the same");

// constructor property can be used same as constructor
var person3 = new person2.constructor();
assert(person3 instanceof Person, "person3 is instance of Person");


// property attached to prototype after obj instantiation is still available
Person.prototype.goToPlay = function () {
    return true;
};
assert(person2.goToPlay(), "property attached to prototype after object instantiation is still available ");

// property references are resolved in the object first
// prototype is consulted only if its not able to find it in property
function Actor() {
    this.hasActed = false;
    this.act = function () {
        return !this.hasActed;
    };
};
var actor1 = new Actor();
Actor.prototype.act = function...