Basic Computed Properties

by rmadhuram

JavaScript

Object.prototype.set = function(key, val) {
    this[key] = val;
};

Object.prototype.get = function(key) {
    var val = this[key];
    if (typeof val === 'function') {
        val = val.call(this);
    }
    return val;
};

/*
 * 
 */
var obj = {
    a: 5,
    b: 7,
    c: function() {
       return this.get('a') + this.get('b');
    },
    
    d: function() {
       return this.get('c') + this.get('a'); 
    }
};


console.log(obj.get('d'));
obj.a = 11;
console.log(obj.get('d'));