JS Where to store methods

by Ivan Gerasimenko

HTML

<!-- added to LINKS -->

JavaScript

var log = function(msg) { console.log(msg); };
// do store in prototype (not in Object)
// reasons:
//  - methods available for all instances (without coping)
//  - easy to modify
//  - efficient memory usage
// disadv:
//  - cannot access private fields

var User = function(name) {
    this.name = name;
    var regDate = new Date(); // private field
    this.getRegDate = function() { // only accessable
        return regDate;            // from function of instance
    }
}

User.prototype.intro = function() {
    return 'My name is ' + this.name;
}

var u = new User('Pit');

log( u.intro() );
log( u.getRegDate() );