Thursday, October 31, 2013

The OOP Enssences in JavaScript

Instantization

// The following code shows how Firefox implements the "new" operator
function Point(x, y){ 
    this.x = x; this.y = y;
}
function ObjectFactory(){
    var obj = {};
    var Constructor = Array.prototype.shift.call( arguments );
    if(typeof Constructor.prototype === 'number')
        obj.__proto__ =  Object.prototype;
    else
        obj.__proto__ =  Constructor.prototype;
    var ret = Constructor.apply(obj, arguments);
    return typeof ret === 'object' ? ret : obj;
}

// This is equivalent to: var p = new Point(0, 0);
var p = ObjectFactory(Point, 0, 0);

Inheritance

// The following code is generated by CoffeeScript to 
// implement subclass inheritance
var __extends = function(child, parent) {
    for (var key in parent) {
      if (Object.prototype.hasOwnProperty.call(parent, key)) {
        child[key] = parent[key];
      }
    }
    function ctor() { this.constructor = child; }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor;
    child.__super__ = parent.prototype;
    return child;
};

// Our code
var Person = function(name) {
    console.log('Hi, I am ' + name + '!'); 
    this.name = function(){ return name };
};
var Student = function() {
    Student.__super__.constructor.apply(this, arguments);
};
__extends(Student, Person);    // make Student a subclass of Person
var me = new Student('Eric');  // "Hi, I am Eric!"
console.log(me.name());        // "Eric"

No comments:

Post a Comment