OBJECTS MIT-AITI copyright 2001
Introduction Object and Properties Constructors and Methods Prototypes and Inheritance Object-Oriented JavaScript Objects as Associative Arrays Object Properties and Methods
Objects and Properties Objects are compound data types which aggregate multiple data values into single units. Thus it’s a collection of properties each of which has a name and a value.
Creating Objects Objects are created using the new operator. The operator is followed by a constructor that serves to initialize the object. var o = new Object(); They can also be created using object literals-it consists of a comma-seperated list of property specfications enclosed with curly braces.
Each property specification consists of a name followed by a colon and the property value. var girlfriend = { name: “L”, age:21, married: false };
Accessing Object Properties You normally use the. Operator to access object properties. The value on the left side of the. is the variable that contains the object reference whilst that on the right contains reference to the property To access name of my girlfriend girlfriend.name
Object properties work much in the same ways as variables you can read them or right values onto them. You can create a new property by simply assigning a value to it. We do not use the var keyword to create object properties as we do with variables
Example //create new girl and store //reference to her in a variable var girl = new Object(); //Set a property in the objects girl.name=“GabrielMusah”; //Set some more properties and //note nested objects girl.boyfriend = new Object(); girl.boyfriend.name =“Careca”; //Read some property values //from the object (alert “Girl profile: \n” + “name: \t” + girl.name + “\nboyfriend: \t” + girl.boyfriend.name );
Undefined Object Properties If you try to read the value of an undefined property you end up retrieving the special JavaScript undefined value. To delete the the property of an object you use the delete operator. delete girlfriend.boyfriend;
Enumerating Object Properties for/in loop provides a way to loop through the properties of an object. Useful when debugging scripts or when working with scripts whose properties are not initially known.
Example function listGirlPropertyNames(obj) { var names = “”; for(var i in obj) names += I + “\n”; alert(names); }
Example:for/in function listPropertyNames(obj){ var names = “”; for (var i in obj) names += i + “\n”; alert(names); }
Constructors A constructor is a JavaScript function with two special features: Its invoked through the new operator It’s passed a reference to a newly created empty object as the value of the special this keyword and its responsible for performing appropriate initialization for that new object.
Example //Constructor initializes the object referred to by “this” function girlfriend(name,age) { this.name = name; this.age = age; } //Invoke the constructor to build two girlfriend objects;I.e Note that we //pass age and name so that each girlfriend object is initialized properly var girlfriend1 = new girlfriend(Nimo,20); var girlfriend2 =new girlfriend(GabrielMusah,21);
Note that a constructor simply initializes the specified object and does not have to return it. Constructor functions don’t typically have return values but they can return an object value- if it does so, the returned object becomes the value of the new expression.
Methods A method is a JavaScript function invoked through an object to define a method m from using a function f and object o; o.m = f; the method is invoked as follows o.m(); //Where the parenthesis contains number of arguments
The object method through which the method is invoked becomes the value of the this keyword within the body of the method. There is no technical difference between functions and methods. The difference lies in design and intent:Methods are written to operate on this object while functions are usually stand alone and do not use this object.
Example //This function uses the this keyword thus it // has to be made the method of some object function changeBoyfriend(name){ this.girl.boyfriend.name = name; } var girl = new girl(kate,21); //Define method by assigning the function //as the objects property girl.changeBoyfriend = changeBoyfriend; //invoking the method girl.changeBoyfriend(“gordon”);
The above way of assigning a method to an object is not efficient as every girl object we create has to be assigned the method as a property We can solve this problem by assigning the methods as object properties in the object constructors so that each new created object has the method.
Example This function uses the this keyword thus it // has to be made the method of some object function changeBoyfriend(name){this.girl.boyfriend.name = name;} function marry(){this.married = true;} function girl(name,age){ this.name=name; this.age;//Initializing Object Properties //Define methods for the object this.marry=marry; this.changeBoyfriend = changeBoyfriend;} var girl = new girl(kate,21); var girl1 = new girl(GabrielMusah,21); girl.changeBoyfriend(“gordon”); girl1.changeBoyfriend(“Manjii”);
This example also has a short coming. The constructor sets 4 properties of each and every girl object it initializes. This happens even though 2 of the properties are common to every object. This consumes a lot of memory
Prototypes and Inheritance Its inefficient to assign common methods to all objects that a constructor initializes. Each class has one prototype object with one set of properties. There are potentially many instances of a class each of which inherits those prototype properties.
Prototypes Every object has a property object from which it inherits its properties. To specify the prototype object for a class of objects we set the value of the prototype property of the constructor function to the appropriate object.
Properties specified in the prototype object are not copied into each object that is created but appear as if they are properties of the object referring to them. Objects inherit properties added to its prototype even after the object is created
Property inheritance occurs only when you read property values and not when you write them. Because prototype properties are shared by all objects of a class, it generally makes sense to use them only to define properties that are the same for all objects within the class e.g. constant variables and methods
Example Suppose we define a Circle() constructor function to create objects that represents guys The prototype object for this object is Circle.prototype and therefore we can define the constant Circle.prototype.pi = ; function Circle(x,y,r){ this.x =x; this.y=y; this.r=r;} Circle.prototype.pi = ; function Circle_circumfrence(){ return 2* this.pi* this.r;} Circle.prototype.circumfrence = Circle_circumfrence; var c1 = new Circle(0.0,0.0,1.0); var c2 = new Circle (1.0,1.0,2.0); var circum1 = c1.circumfrence();
Built in Classes Built in classes have prototype objects too and you can assign values to them. A new method for all string object String.prototype.endsWith=func tion(c){return c==this.charAt(this.length-1))} You can now use this method as follows var message = “study”; message.endsWith(‘y’);
Object Oriented Javascript Instance Variables: Every object has its own separate copies of instance variables- by default any object property is an instance variable. Instance method much like an instance variable except that it’s a method. Class variables are variables associated with the class itself. Class methods are associated with a class rather than an instance
Objects as Associative Arrays You can use the [] operator to access the properties of an object. Object.property and Object[“property”] have the same value. The property name in the [] operator is a string.Thus you could change the property being accessed by changing the string.
Example var addr = “”; for(i=0;i<4;i++) { addr += customer[“address” + i]; }
Associative Arrays Data structures that allow you to dynamicallyassociate arbitrary data values with arbitrary strings. var value = 0; for(stock in portfolio){ Value+=get_share_value(stock) * portfolio[stock]; }
Object properties and Methods Constructor Property toString() Method valueof() Method
Constructor Property Every object has a constructor object that refers to the constructor that initialized it. Var Jane = new Girl(Jane,21) Jane.constructor == Jane //Evaluates to true
toString() Method It takes no arguments and returns a string that represents the type and/or value of the object its invoked on. The default toString() method is not very informative therefore one usually defines their own toString methods for their class of objects: Circle.prototype.toString = function(){return “[Circle of radius” + this.r + “]”;}
valueOf() Method Similar to toString() method; called when JavaScript needs to convert an object to a primitive type, typically a number. Objects by definition are not primitive types therefore when the valueOf method is invoked on most methods it returns the object itself.