OOJS: Prototypes

(this lesson is very technical; inheritance is a better place to start)

Prototypes

Example:


var mammal = {lactates: true, legs: 4};

var bat = Object.create(mammal);
bat.legs = 2;
bat.legs;     // 2
bat.lactates; // true

var horse = Object.create(mammal);
horse.legs;     // 4
horse.lactates; // true

octohorse = Object.create(horse);
octohorse.legs = 8;
octohorse.legs  // 8

if (!Object.create) {
    (function() {
        function F() {}
        Object.create = function(parent) {
            F.prototype = parent;
            return new F();
        };
    }());
}

Names and Types

Using prototypes to extend core objects

Array.prototype.sum = function() {
    var total = 0;
    for (var i=0; i<this.length; ++i) {
        total += this[i];
    }
    return total;
};
[1,2,3].sum()  // 6

Q: what is "this" in the above code?

String.prototype.reverse = function() {
    return this.split('').reverse().join('');
}
"abc".reverse() // returns "cba"

Q: What object is actually doing the reversing?

apply Yourself

var add = function(x,y) { return x+y; }
add.apply(null, [2, 3]); // returns 5

var square = function() { return this.value * this.value; }
var x = {value: 10}
square.apply(x);  // returns 100
var y = {value: 20}
square.apply(y);  // returns 400

var increaseBy = function(amount) { return this.value + amount; }
increaseBy.apply(x, [4]); // returns 14
increaseBy.apply(y, [5]); // returns 25

 Previous Lesson Next Lesson 

Outline

[menu]

/