Playing with oop js

by de Montalembert Jonathan

JavaScript

age = 28;
var Person = function (opt) {
    if(!opt) return false;
    this.name = opt.name || '';
    this.age = opt.age || '';
};
Person.prototype.get = function (str) {
    return this[str]
};
Person.prototype.type = 'Person';

var p = new Person({
    name: 'jon',
    age: 27
});

// case bound
var get = p.get;
console.log(get('age'), get.call(p, 'age'));
// First returns 28 because default this is window
// Second returns 27 because this is p

console.log(p.get('age'));
// successfuly returns 27 because this is p and p.age is 27


// case inheritence
var Student = function (opt) {
    var ar = [];
    ar.push(opt);
    Person.apply(this, ar); // call the Person constructor
};

Student.prototype = new Person(); // inherit all the methods from Person
Student.prototype.constructor = Student; // we want to copy all the methods but constructor

var s = new Student({
    name: 'jon'
});

Student.prototype.type = 'Student'; // overwrite type
console.log(s.get('name'));
console.log(s.type, p.type);
console.log(s.constructor); // returns the function assigned to Person