Why do unprivileged methods?

I am learning JavaScript, and I cannot understand why you should use methods that are not "privileged", that is, not defined in the constructor, but rather a prototype of the class.

I understand the idea of ​​encapsulation and that’s all, but you never encapsulate parts of a class from the rest of it to most of the OO world.

+5
source share
1 answer

When a function is defined in the constructor, each instance of this 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 in a prototype, a function is created only once, and one instance of this 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
};

, , . , . : http://www.crockford.com/javascript/private.html

+18

All Articles