2

If you have a constructor function like

var SomeClass = function(){
    this.a= "";
    this.b= "";
}

then let's say you add another method using prototype

SomeClass.prototype.fn = function fn(){
    console.log(this.a);
 };

Why use prototype where you can just add this method to your constructor function?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
ibrahim
  • 135
  • 3
  • 9
  • Possible duplicate of [How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – alex Aug 12 '16 at 10:56
  • I've updated your question to remove syntax errors (and follow normal JavaScript naming standards; constructor functions are initially capitalized by convention). `class` is a keyword, you can't use it as a variable name. – T.J. Crowder Aug 12 '16 at 10:57
  • thanks It was for the sake of explanation . – ibrahim Aug 12 '16 at 11:29

3 Answers3

1

There are a few benefits:

  1. It creates one fn function, reused by all objects created with that constructor; this is more memory-efficient than a separate function on every object.

  2. Having the objects keep a dynamic link to their prototype means when you add methods to the prototype, they're available to objects that already exist.

  3. Having just one function all relevant objects reuse means you can update that function if necessary at runtime, in just one place, and have the updated function used by all relevant objects, even ones that already exist.

  4. Having it available on the constructor's prototype property means it can be used on other objects, not created via the constructor; this is frequently used to good effect, such as:

    Array.prototype.forEach.call(
        document.querySelectorAll("div"),
        function(div) {
            // ...
        }
    );
    
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Ad 3: But if the method is inside the constructor function then you update it only in one place too, right? –  Aug 12 '16 at 11:00
  • 1
    @AdrianWydmanski: Sorry, I was unclear. You're thinking in terms of modifying the source. I'm talking about dynamically changing the structure at runtime, which is one of the more powreful aspects of JavaScript. – T.J. Crowder Aug 12 '16 at 11:01
0
var myClass = function(){
    this.a = "";
    this.b = "";
    this.fn = function(){
        console.log(this.a);
    }
};

Beause now if you create 1000 objects, they will all share the same fields repeat over and over again: { a: "", b: "", fn: myClass/this.fn() }.

This is memory consuming and is a bad practice. When you delegate fn to class.prototype, the code is not repeated and the objects are "lighter": { a: "", b: "" }, but they still can use fn method.

0

Because when you create an object out of the function with the new keyword

tesObject= new Class();

you everytime recreate the function in every object.

So it uses more memory and its less peformant.

Simon Müller
  • 451
  • 1
  • 4
  • 17