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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With