OBJECTS MIT-AITI copyright 2001. Introduction Object and Properties Constructors and Methods Prototypes and Inheritance Object-Oriented JavaScript Objects.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
VBA Modules, Functions, Variables, and Constants
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Lecture 3. 2 Introduction Java is a true OO language -the underlying structure of all Java programs is classes. Everything must be encapsulated in a class.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
WEB DESIGN AND PROGRAMMING Introduction to Javascript.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
JavaScript – Part II Data Types and Operations George Mason University June 3, 2010.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
JavaScript, Fourth Edition
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Session 7 JavaScript/Jscript: Arrays Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
Using Client-Side Scripts to Enhance Web Applications 1.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
Learners Support Publications Classes and Objects.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Martin Kruliš by Martin Kruliš (v1.0)1.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Objects.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Classes, Interfaces and Packages
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Controlling Computers with Programs When you create a computer program you are creating a set of instructions that tell the computer exactly and completely.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
JavaScript and Ajax (Control Structures) Week 4 Web site:
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Chapter 4 Client-Side Programming: the JavaScript Language
COMP 170 – Introduction to Object Oriented Programming
Java Primer 1: Types, Classes and Operators
Scope, Objects, Strings, Numbers
JavaScript: Functions.
Programmazione I a.a. 2017/2018.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
JavaScript and Ajax (Expression and Operators)
ARRAYS MIT-AITI Copyright 2001.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Objects as Variables Featuring the Date Object
Lecture 22 Inheritance Richard Gesick.
T. Jumana Abu Shmais – AOU - Riyadh
Classes and Objects.
Classes, Objects and Methods
Structures, Unions, and Enumerations
Presentation transcript:

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.