Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why make non-privileged methods?

Tags:

javascript

I'm learning JavaScript, and I can't understand why you'd make methods that aren't 'privileged,' that is, that aren't defined in the constructor but rather the class' prototype.

I understand the idea of encapsulation and all, but you never encapsulate parts of a class from the rest of it in most of the OO world.

like image 282
Aaron Yodaiken Avatar asked Jun 18 '10 01:06

Aaron Yodaiken


1 Answers

When a function is defined in a constructor, a new instance of that function is created each time the constructor is called. It also has access to private variables.

var myClass = function() {
    // private variable
    var mySecret = Math.random();

    // public member
    this.name = "Fred";

    // privileged function (created each time)
    this.sayHello = function() {
        return 'Hello my name is ' + this.name;
        // function also has access to mySecret variable
    };
}

When a function is defined on the prototype, the function is created only once and the single instance of that function is shared.

var myClass = function() {
    // private variable
    var mySecret = Math.random();

    // public member
    this.name = "Fred";
}

// public function (created once)
myClass.prototype.sayHello = function() {
    return 'Hello my name is ' + this.name;
    // function has NO access to mySecret variable
};

So defining a function on the prototype produces less objects which can give you better performance. On the other hand, public methods do not have access to private variables. Further examples and reasoning are available here: http://www.crockford.com/javascript/private.html

like image 72
Greg Avatar answered Oct 18 '22 01:10

Greg