javascript basics - IV

javascript basics - classes, instance members, private members, properties, static members, prototype object.

by deshpandeakhil

JavaScript

var f = function(arg) {
    if (arg != null) {
        document.write(arg);
        document.write("<br/>");
    } else if (arg == undefined) {
        document.write("undefined<br/>");
    }
    else {
        document.write("<br/>");
    }
};

// classes
// as convention use Person instead of person to denote a class. This function returns an object which has name, age and created properties.
function Person(name, age){
    //public
    this.name = name;
    this.age = age;
    this.created = new Date();
    this.dowork = function(arg){f(arg);};
        
    //private member is declared by using the var keyword
    var _pvtMember = "something private";
    
    //properties
    Object.defineProperty(this, "propMember", {
        get: function() {return _pvtMember;},
        set: function(value) {_pvtMember = value;}    
    });
    
    //defining a static member
    Person.staticMember = "static Member";
    Person.staticFunc = function(){f(this.name);};
    
    //Prototype object - every js 'type' is associated with a prototype object. the prototype is just an object to which properties can be added. all instances of a 'type' can share the properties or functions of prototype. In case of static, instances can not access the static properties or functions.
    //sharing data amongst instances
    Person.prototype.sharedProp = "shared prop";
    //sharing functions amongst instances
    Person.prototype.sharedFunc = function(){f(this.name);};
};
var personInst = new Person("Roger Federer", 32);
f(personInst.name + " " + personInst.age + " " + personInst.created);
f(personInst._pvtMember); //unable to access this as its private
f(personInst.propMember); //able to access this property
personInst.propMember = "something else"; //using the setter property
f(personInst.propMember);
f(personInst.staticMember);//person instance cant access because its static
f(Person.staticMember);//works because its accessed via the class Person instead of instance...