2

Using this

var Class1 = function() {       
        this.test1 = function() {
        };
    };

and the following

function Class1() { 
};

Class1.prototype.test1 = function() {

};

Is there difference between those two?

Adam Lee
  • 24,710
  • 51
  • 156
  • 236

4 Answers4

3

The first one makes a separate copy of the function for each class instance.
It also allows the function to use closure'd variables from the constructor.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

There is difference which affects performance as well.

The first one will add function to each instance of the created class while latter won't. For the latter method, JavaScript will look into prototype chain of the object and would return the needed method, the test1 in your case.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

Yes, there are. See

for the two (independent) differences.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Using the later one in efficient.

Functions in JavaScript are objects. Every object in JavaScript holds a hidden piece of state – a reference to another object known as the object’s prototype.

Using prototype multiple objects can maintain references to the same prototype object.

This is a great reference to know how prototype in js works.

Katti
  • 2,013
  • 1
  • 17
  • 31