Let??™s take a look at an example:
function foo(){ }
var bar = new foo();
Let??™s extend the last example by adding new properties to each object:
function foo(){ }
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"
Likewise, if you want to add new methods, you can do the following:
function foo(){ }
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"
function myfunc(){ }
bar.mymethod = myfunc; // this assigns the function
bar.mymethod(); // this calls the method
A variation on this is to use an anonymous function:
function foo(){ }
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
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 22
In this last example, using an anonymous function means that you don??™t have to worry
about the function myfunc() conflicting with any other objects or variables on the page. It also
keeps the code cleaner.
nNote In JavaScript, functions are objects. As you can see in this last example, I attached a value attribute
to the foo function.
Dot Notation and Bracket Notation
JavaScript offers two ways to access the properties of an object.
Pages:
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67