I'm part of a small study group at work that's trying to get a better grasp on what makes JavaScript tick. In our recent discussions about objects, we've learned that an object's public methods are recreated each time an object is instantiated, while methods assigned to the object's prototype are only created once and inherited by all instances. From what I understand, both public methods and those assigned to the prototype are publicly accessible.
The question I have, then, is why bother creating public methods at all if adding to the prototype is apparently more efficient? What benefit does the public method provide that the prototype doesn't?
Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting. Public instance fields are added with Object.
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
Answering this specifically:
What benefit does the public method provide that the prototype doesn't?
A method added within the constructor has access to private information, eg:
function Student() { var name = 'Bob'; this.GetName = function() { return name; } } Student.prototype.SomeOtherPublicMethod = function() { //no access to name }
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