admin管理员组

文章数量:1365850

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.

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.

Share Improve this question asked Jun 18, 2010 at 1:30 Aaron YodaikenAaron Yodaiken 19.6k33 gold badges108 silver badges187 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 18

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./javascript/private.html

本文标签: javascriptwhy make nonprivileged methodsStack Overflow