Tuesday 2 April 2013

JavaScript Object Creation

/*
 * JavaScript object functional constructor.
 */
var constructStudent = function(name, age, caddress, paddress) {
    this.name = name;
    this.age = age;
  
    Object.defineProperties(this, {
        "Caddress" : {
            enumerable : false,
            value : caddress
        },
        "Paddress" : {
            enumerable : true,
            value : paddress
        },
        "University" : {
            value : "UPTU",
            writable : false
        },
        "Country" : {
            value : "India",
            configurable : false,
        },
    });
    return this;
}

function kick() {
    console.log('kick');
}
/*
 * prototype of javaScript object.
 */
constructStudent.prototype = {
    collegeName : "GLBITM",
    markCalculator : function(math, science) {
        var totalMarks = math + science;
        return totalMarks;
    },
    resultCalculator : function(totalMarks) {
        var total = totalMarks;
        if (total > 33) {
            console.log("pass");
        } else {
            console.log("fail");
        }

    }

}
var firstBoy = new constructStudent('anshul', '23', 'bangalore', 'mahoba');
firstBoy.name = "rahul";
firstBoy.University = "MTU";
console.log(firstBoy.name);
console.log(firstBoy.University);
var total = firstBoy.markCalculator(22, 56);
firstBoy.resultCalculator(total);
console.log(total);
console.log(firstBoy.collegeName);
console.log(Object.keys(firstBoy));
console.log(Object.getOwnPropertyNames(firstBoy));
console.log(firstBoy.hasOwnProperty('collegeName'));
var result = [];
for ( var propName in firstBoy) {
    result.push(propName);
}
console.log(result);
delete firstBoy.Country;
console.log(Object.getOwnPropertyNames(firstBoy));
console.log(firstBoy.propertyIsEnumerable('collegeName'));