Using “prototype” for variables

Most of the time (tutorials mainly), I have seen "prototype" used for methods.

I'm pretty sure it can also be used for variables (perhaps the most useful for setting "default values"). Is there a reason it's not often used for functions? Is it bad practice, or are there noticeable performance differences?



Think about it the other way round: Why would you want to store an object's attribute in its prototype?

There's two answers:

  1. Save memory. Defining methods on every instance would consume an awful amount, since technically each instance would have its own method. The cost is considerably lower for simple data types.
  2. Shared access. Instances may need to share access to a common attribute. However, this is not possible for simple data types, since those are not stored by reference.

As gilly3 mentioned, 2. may just accidentally happen if you're not absolutely sure what you're doing. (Oh yes, it happened to me...)

Best practice:

  • Methods go to the prototype
  • Attributes go to the instances, unless you need shared access (and the attribute is object-typed).


  • Shared access should be implemented using closures, not "class variables"


And yes, the performance of using prototype is slightly worse than the other way. BUT you should never try to optimize things like that, since the performance gain is almost unnoticeable, yet the readability and maintainability of your code may suffer significantly.


Off the top of my head, you lose the functionality of hasOwnProperty(), which can be useful if you are ever doing a for ... in loop on your object. Consider these two objects:

function MyObject() { ... }
MyObject.prototype.someProperty = 1;

var a = new MyObject();
var b = new MyObject();
b.someProperty = 2;

a.hasOwnProperty("someProperty"); // false
b.hasOwnProperty("someProperty"); // true

That may or may not matter for your situation.

Edit: Thought of another one. If you store objects in your prototype and an instance of that object changes a property on that object, it will affect all other instances:

function MyObject() { ... }
MyObject.prototype.someProperty = { value: 1 };

var a = new MyObject();
var b = new MyObject();

b.someProperty.value = 2;
a.someProperty.value; //  2!! not 1

The prototype object of JavaScript, introduced starting in JavaScript 1.1, is a prebuilt object that simplifies the process of adding custom properties/ methods to all instances of an object

You can add default properties, here is an example:

function myObject()

myObject.prototype = 

    constructor : function ()
        this.MyProperty1 = "123456"; //default property
        this.MyProperty2 = "bla";    //default property

Let me know if this helps...


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.