S
S
Stadinov Denis2015-09-08 17:05:37
JavaScript
Stadinov Denis, 2015-09-08 17:05:37

Difference of Complex.add from Complex.prototype.add?

Good afternoon community!
I'm reading the JavaScript book (David Flanagan, 5th edition) and in chapter 9 (9.3.6 chapter, 176 pages) there is an example of how to create a "class".
Help me understand the difference between .add method and .add prototype

function Complex(real, imaginary) 
{this.x = real; this.y = imaginary;};

Complex.prototype.add = function(that)
{return new Complex(this.x + that.x, this.y + that.y); };

Complex.add = function(a, b)
{return new Complex(a.x + b.x, a.y + b.y); };

As mentioned earlier in the book, first a method is searched in the class, and then in the prototype, but we have it there and there, but with a different interface.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Taratin, 2015-09-08
@Taraflex

var complex1 = new Complex(1,2);
var complex2 = new Complex(3,4);


var c3 = Complex.add(complex1, complex2);//сработает Complex.add = function(a, b)

var c4 = complex1.add(complex2);//сработает Complex.prototype.add = function(that)

var c5 = complex1.add(complex1, complex2);//сработает Complex.prototype.add = function(that) но параметр 2 просто проигнорируется и получим complex1 + complex1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question