javascript prototype vs constructor function

Solutions on MaxInterview for javascript prototype vs constructor function by the best coders in the world

showing results for - "javascript prototype vs constructor function"
Bria
13 Apr 2016
1function Class () {}
2Class.prototype.calc = function (a, b) {
3    return a + b;
4}
5
6// Create 2 instances:
7var ins1 = new Class(),
8    ins2 = new Class();
9
10// Test the calc method:
11console.log(ins1.calc(1,1), ins2.calc(1,1));
12// -> 2, 2
13
14// Change the prototype method
15Class.prototype.calc = function () {
16    var args = Array.prototype.slice.apply(arguments),
17        res = 0, c;
18
19    while (c = args.shift())
20        res += c;
21
22    return res; 
23}
24
25// Test the calc method:
26console.log(ins1.calc(1,1,1), ins2.calc(1,1,1));
27// -> 3, 3