SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 103 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"


Adding Methods and Properties
Now that you have an object, you need to give it methods and properties. I covered this in the
last chapter, but let??™s go over it again because I??™ll be showing you a few different ways to do it:
var CustomObject = function(){ };
CustomObject.value = 5;
CustomObject.methodName = function(){ alert(this.value) };
CustomObject.methodName(); // it's 5!
This is great, but actually doesn??™t help you much because these methods and properties
are accessible only on this object and won??™t be retained when you create a new object from
this function (as the following example shows you):
var newObject = new CustomObject();
newObject.methodName(); // undefined... that didn't work.
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 59
To add properties to a class, use the this keyword from within the function (I??™ll explain
why in a minute):
var CustomObject = function(){
this.value = 5;
this.methodName = function(){ alert(this.value) };
};
Now that your class has properties, new objects instantiated from this class will have
these new properties, too:
var newObject = new CustomObject();
newObject.methodName(); // it's 5!
The properties you defined are available in any new object you instantiate.
The Mechanics of Object Instantiation
When the function is executed with the new keyword, a new object is instantiated and used
as the context from within the function.


Pages:
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115