Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use public methods in JavaScript objects? [duplicate]

Tags:

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?

like image 358
AurumPotabile Avatar asked Oct 08 '15 12:10

AurumPotabile


People also ask

What is public in JavaScript?

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.

How are object properties assigned in JavaScript?

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.


1 Answers

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 } 
like image 59
James Thorpe Avatar answered Sep 20 '22 16:09

James Thorpe