It also means that you can attach new properties and methods to the prototype and they??™ll
become available for all objects, even ones that were already cloned. This is done by using
the prototype property of an object.
Let??™s take the last example and build on top of it:
var foo = function(){ }
var bar = new foo();
foo.value = 5;
alert(foo.value); // shows the value property "5"
bar.value = 6;
alert(bar.value); // shows the value property "6"
bar.mymethod = function (){ }; // this assigns the function
bar.mymethod(); // this calls the method
foo.prototype.othervalue = 6;
alert(bar.othervalue); // shows "6"
As you can see, I attached the new property to the prototype of my original object foo, but
it is also available under my existing object bar. (This concept is discussed in more detail in
Chapter 3.)
Passing by Value or by Reference
There are two ways in which values are passed into a function: by value or by reference. When
passing a variable, a copy of the value is made and used within the function. Any changes to
the variable are reflected only within the function. The variable outside of the function
remains untouched. This is passing by value:
var foo = 5;
function bar(val)
{
val = 6; // I'm changing it to 6!
}
bar(foo);
alert(foo); // it's still 5
Passing an object in as a parameter will pass it in by reference. That means that you have
full access to the object??™s methods and properties, and any changes made to the object will be
reflected outside of the function.
Pages:
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69