performance – Javascript when to use prototypes-ThrowExceptions

Exception or error:

I’d like to understand when it is appropriate to use prototype methods in js. Should they always be used? Or are there cases where using them is not preferred and/or incurs a performance penalty?

In searching around this site on common methods for namespacing in js, it seems that most use a non-prototype based implementation: simply using an object or a function object to encapsulate a namespace.

Coming from a class-based language, it’s hard not to try and draw parallels and think that prototypes are like “classes” and the namespace implementations I mentioned are like static methods.

How to solve:

Prototypes are an optimisation.

A great example of using them well is the jQuery library. Every time you obtain a jQuery object by using $('.someClass'), that object has dozens of “methods”. The library could achieve that by returning an object:

return {
   show: function() { ... },
   hide: function() { ... },
   css: function() { ... },
   animate: function() { ... },
   // etc...
};

But that would mean that every jQuery object in memory would have dozens of named slots containing the same methods, over and over.

Instead, those methods are defined on a prototype and all jQuery objects “inherit” that prototype so as to gain all those methods at very little runtime cost.

One vitally important part of how jQuery gets it right is that this is hidden from the programmer. It’s treated purely an optimisation, not as something that you have to worry about when using the library.

The problem with JavaScript is that naked constructor functions require the caller to remember to prefix them with new or otherwise they typically don’t work. There is no good reason for this. jQuery gets it right by hiding that nonsense behind an ordinary function, $, so you don’t have to care how the objects are implemented.

So that you can conveniently create an object with a specified prototype, ECMAScript 5 includes a standard function Object.create. A greatly simplified version of it would look like this:

Object.create = function(prototype) {
    var Type = function () {};
    Type.prototype = prototype;
    return new Type();
};

It just takes care of the pain of writing a constructor function and then calling it with new.

When would you avoid prototypes?

A useful comparison is with popular OO languages such as Java and C#. These support two kinds of inheritance:

  • interface inheritance, where you implement an interface such that the class provides its own unique implementation for every member of the interface.
  • implementation inheritance, where you extend a class that provides default implementations of some methods.

In JavaScript, prototypical inheritance is a kind of implementation inheritance. So in those situations where (in C# or Java) you would have derived from a base class to gain default behaviour, which you then make small modifications to via overrides, then in JavaScript, prototypical inheritance makes sense.

However, if you’re in a situation where you would have used interfaces in C# or Java, then you don’t need any particular language feature in JavaScript. There is no need to explicitly declare something that represents the interface, and no need to mark objects as “implementing” that interface:

var duck = {
    quack: function() { ... }
};

duck.quack(); // we're satisfied it's a duck!

In other words, if each “type” of object has its own definitions of the “methods”, then there is no value in inheriting from a prototype. After that, it depends on how many instances you allocate of each type. But in many modular designs, there is only one instance of a given type.

And in fact, it has been suggested by many people that implementation inheritance is evil. That is, if there are some common operations for a type, then maybe it’s clearer if they are not put into a base/super class, but are instead just exposed as ordinary functions in some module, to which you pass the object(s) you want them to operate on.

###

You should use prototypes if you wish to declare a “non-static” method of the object.

var myObject = function () {

};

myObject.prototype.getA = function (){
  alert("A");
};

myObject.getB = function (){
  alert("B");
};

myObject.getB();  // This works fine

myObject.getA();  // Error!

var myPrototypeCopy = new myObject();
myPrototypeCopy.getA();  // This works, too.

###

One reason to use the built-in prototype object is if you’ll be duplicating an object multiple times that will share common functionality. By attaching methods to the prototype, you can save on duplicating methods being created per each new instance. But when you attach a method to the prototype, all instances will have access to those methods.

Say you have a base Car() class/object.

function Car() {
    // do some car stuff
}

then you create multiple Car() instances.

var volvo = new Car(),
    saab = new Car();

Now, you know each car will need to drive, turn on, etc. Instead of attaching a method directly to the Car() class (which takes up memory per each instance created), you can attach the methods to the prototype instead (creating the methods only once), therefore giving access to those methods to both the new volvo and saab.

// just mapping for less typing
Car.fn = Car.prototype;

Car.fn.drive = function () {
    console.log("they see me rollin'");
};
Car.fn.honk = function () {
    console.log("HONK!!!");
}

volvo.honk();
// => HONK!!!
saab.drive();
// => they see me rollin'

###

Put functions on a prototype object when you’re going to create lots of copies of a particular kind of object and they all need to share common behaviors. By doing so, you’ll save some memory by having just one copy of each function, but that’s only the simplest benefit.

Changing methods on prototype objects, or adding methods, instantly changes the nature of all the instances of the corresponding type(s).

Now exactly why you’d do all these things is mostly a function of your own application design, and the kinds of things you need to do in client-side code. (A whole different story would be code inside a server; much easier to imagine doing more large-scale “OO” code there.)

###

If i explain in class based term then Person is class, walk() is Prototype method. So walk() will have its existence only after you instantiate new object with this.

So if you want to create the copies of object like Person u can create many users Prototype is good solution as it saves memory by sharing/inheriting same copy of function for each of the object in memory.

Whereas static is not that great help in such scenario.

function Person(){
this.name = "anonymous";
}

// its instance method and can access objects data data 
Person.prototype.walk = function(){
alert("person has started walking.");
}
// its like static method
Person.ProcessPerson = function(Person p){
alert("Persons name is = " + p.name);
}

var userOne = new Person();
var userTwo = new Person();

//Call instance methods
userOne.walk();

//Call static methods
Person.ProcessPerson(userTwo);

So with this its more like instance method.
The object’s approach is like Static methods.

https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *