Assume there is a constructor for an object representing a complex number called Complex that takes two arguments: x the "real part" of the number and y the imaginary part of the number. Assume that the constructor function can be called without specifying x or y (i.e. leaving them as undefined) if desired. Assume further that the Complex objects have two methods, add and multiply, each of which takes two arguments that are Complex objects. Create an object called obj1 representing the complex number 3+4i (real part is 3 and imaginary part is 4). Create a second object called obj2 representing the complex number 1-6i. Create a third object called obj3, and set it to the sum of obj1 and obj2. Create a fourth object called obj4 and set it to the product of obj1 and obj2.

javascript programming
exercise: methods 07

x
document.write("obj4 is: "+obj4.realPart+" + "+obj4.imagPart+"i and should be: 27-14i<br>");
 
1
<html>
2
<script> 
3
4
function Complex(x,y) {
5
  this.realPart = x;
6
  this.imagPart = y;
7
}  
8
9
var ComplexProto = {
10
  add : function(a,b) {
11
    this.realPart = a.realPart + b.realPart;
12
    this.imagPart = a.imagPart + b.imagPart;
13
  },
14
  multiply : function(a,b) {
15
    this.realPart = a.realPart*b.realPart - a.imagPart*b.imagPart;
16
    this.imagPart = a.realPart*b.imagPart + a.imagPart*b.realPart;
17
  }
18
};
19
20
Complex.prototype = ComplexProto;
21
22
// Add code here
23
24
25
26
// Code test
27
28
document.write("Test Results<br>");
29
30
document.write("obj1 is: "+obj1.realPart+" + "+obj1.imagPart+"i and should be: 3+4i<br>");
31
if (obj1.realPart===3 && obj1.imagPart===4)
32
  document.write("pass<br>");
33
else
34
  document.write("FAIL<br>");
35
36
document.write("obj2 is: "+obj2.realPart+" + "+obj2.imagPart+"i and should be: 1-6i<br>");