Primer on Prototypal Inheritance

Oh god... new vs prototype vs constructor just kill me. http://ejohn.org/apps/learn/#76

by Augustus Yuan

JavaScript

// delegation with Object.create
var circle = {
    radius: 5,
    create: function (radius) {
        var circle = Object.create(this);
        circle.radius = radius;
        return circle;
    },
    area: function () {
        var radius = this.radius;
        return Math.PI * radius * radius;
    },
    circumference: function () {
        return 2 * Math.PI * this.radius;
    }
};

var circleObjectCreate = circle.create(10);

// delegation with new
function Circle(radius) {
    this.radius = radius;
}

Circle.prototype.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

Circle.prototype.circumference = function () {         
    return 2 * Math.PI * this.radius;
};
var circleNew = new Circle(10);

console.log(circleObjectCreate);
console.log(circleNew);

// Now one thing you'll notice is that one is an Object and one is actually considered a "Circle". This is JavaScript's attempt to make JavaScript more like Java 
console.log('circleObjectCreate instanceof for Object and Circle will pass for the first but for the second...')
console.log(circleObjectCreate instanceof Object);
console.log('circleObjectCreate fails instanceof Circle because it doesn\'t inherit it. In fact we didn\'t even define Circle');
console.log(circleObjectCreate instanceof Circle);
console.log('circleNew instanceof for Object and Circle will pass for both because it inherits the prototype properly');
console.log(circleNew instanceof Object);
console.log(circleNew instanceof Circle);

console.log('So you might be thinking how do we know instanceof or isPrototypeOf for circleObjectCreate? Well in Eric Elliot\'s talk, he talks about how it makes a lot less sense (these two things) in a loose typed system like JavaScript. An alternative is to just add an identifier to the object itself');