gave them the values of the arguments passed to the constructor. Note that x on the
left-hand side of the assignment operator is not the same as the one o n its right-hand
side. The first is a property of the newly created object instance while the second is a
declared parameter of the constructor. Th e same holds for y, of course.
With a constructor like that, it is possible to create some vectors:
var v1 = new Vector(0, 2);
var v2 = new Vector(1, 0);
console.log(v1.x); //Writes 0
console.log(v1.y); //Writes 2
console.log(v2.x); //Writes 1
console.log(v2.y); //Writes 0
Maria: If you called the constructor without arguments, would the properties x and y
be crea te d just the same?
Professor: They wou ld. Recall that the f unction parameters for which you don’t
provide argume nts get th e unde fined values. So both properties would be created
and initialized to the undefined values.
Note that there’s also the arguments object working behind the scenes inside a con-
structor just as it is inside any function body. That allows you to write a c onstructor
that initializes an o bject in more than a single way depending on a number of passed
arguments.
11.4 Constructor Overloading
Professor: I n many object-oriented lang uages, there’s a spe cial mechanism involved
when you pass a dierent number of arguments to functions, called function over-
loading, or c onstructor overload ing if you are overloading construc tors. In a nutshell,
this means that you can define two or more dierent constructors by the same name
and they will be discerned from each other depending exclusively on the number of
arguments passed to them. JavaScript does not support overloading but you can still
implement it with the help of either the argu ments object or the fact that parameters
that do not get argument values are set to the und efined value. For example, you can
write a constructor for our vector class that will be have dierently when you provide
no argu ments:
var Vector = function(x, y) {
if (arguments.length == 0) { //If no arguments are passed, then
this.x = 0; //set both components to zero.
this.y = 0;
}
else { //Otherwise, copy the values of the passed arguments.
this.x = x;
this.y = y;
}
};
11.4. Constructor Overloading 211
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.138.33