JavaScript DHTML/Language Basics/Objects Object Oriented

Материал из Web эксперт
Перейти к: навигация, поиск

Содержание

An object and its constructor

   <source lang="html4strict">

<html> <head> <title>Properties</title> <script type = "text/javascript">

   var aObject = {};
   
   function aObject(a,b,c,d) {
       this.myValueA = a;
       this.myValueB = b;
       this.myValueC = c;
       this.myValueD = d;
   }
   aObject["A"] = new aObject("A","C","F",2.0);
   aObject["B"] = new aObject("B","D","V",2.3);

</script> </head> <body> <script type = "text/javascript" > for (var propt in aObject) {

   document.write(propt+"
");

} </script> </body> </html>

 </source>
   
  


Complete Example of Using the employee, client, and project Objects

   <source lang="html4strict">

<html> <head>

 <title>Using the book object</title>
 <script type="text/javascript">
 
 </script>

</head> <body>

 <script type="text/javascript">
 
 </script>

</body> </html>


 </source>
   
  


Create an object and add attributes

   <source lang="html4strict">

<html> <head>

   <title>The Delete Operator</title>
   <script type = "text/javascript" >
   var aObject = {};
   
   aObject["A"] = new Object;
   aObject["B"] = new Object;
   aObject["C"] = new Object;
   aObject["D"] = new Object;
   
   aObject["A"].myValue = "a";
   aObject["B"].myValue = "b";
   aObject["C"].myValue = "c";
   aObject["D"].myValue = "d";
   </script>

</head> <body id = "mainbody"> <script type = "text/javascript">

   for (obj in aObject) {
       var para = document.createElement("p");
       para.id = obj;
       para.appendChild(document.createTextNode(obj + ": " + aObject[obj].myValue));
       document.getElementsByTagName("body")[0].appendChild(para);
   }
   

</script> </body> </html>

 </source>
   
  


Creating an Object and Using Object Instance Properties and Methods

   <source lang="html4strict">

/* Learn How to Program Using Any Web Browser by Harold Davis Apress CopyRight 2004 ISBN: 1590591135

  • /

<HTML> <HEAD> <TITLE>Instance method demo</TITLE> </HEAD> <BODY>

<SCRIPT> function Rectangle(height, width){ // constructor function this.height = height; this.width = width; } // create the function function calc_Area () { return this.height * this.width; } // turn the function into an object method Rectangle.prototype.calcArea = calc_Area; // instantiate the object var theRectangle = new Rectangle (3, 5); // set an instance property theRectangle.width = 10; // call and display the instance properties and method return document.write("The rectangle instance height is: " + theRectangle.height + "
"); document.write("The rectangle instance width is: " + theRectangle.width + "
"); document.write ("The calcArea method returns: " + theRectangle.calcArea()); </SCRIPT>

</BODY> </HTML>


 </source>
   
  


Creating Objects Dynamically

   <source lang="html4strict">

<html> <head>

 <title>Student Database</title>
 <script type="text/javascript">
 
 </script></head>

<body>

Dyanamic Object Creator

 <form name="form1">
      First Name:      
      <input type=text size=20 maxlength=256 name="FirstName">
    
      Last Name:
      <input type=text size=20 maxlength=256 name="LastName">
    
      Home Phone:
      <input type=text size=20 maxlength=256 name="HomePhone">
    
      Ext.:
      <input type=text size=20 maxlength=256 name="Ext">
    
      Email Address:
      <input type=text size=20 maxlength=256 name="EmailAddress">
   
    
      <input type="button" name="Add" value="Add" onClick="insertRecord()">
      <input type="button" name="ShowAll" value="Show All"
        onClick="showAll()">
   
    
 </form>

</body> </html>


 </source>
   
  


Define and use object

   <source lang="html4strict">


function coworker(name, age) {

   this.name = name;
   this.age = age;

} var emp1 = new coworker("Alice", 23); var emp2 = new coworker("Fred", 32);


var emp1 = {name:"Alice", age:23}; var emp2 = {name:"Fred", age:32};


function showAll() {

   alert("Employee " + this.name + " is " + this.age + " years old.");    

} function coworker(name, age) {

   this.name = name;
   this.age = age;
   this.show = showAll;

} var emp1 = {name:"Alice", age:23, show:showAll}; var emp2 = {name:"Fred", age:32, show:showAll}; emp1.show();


function coworker(name, age) {

   this.name = name;
   this.age = age || 0;
   this.show = showAll;

}


function verify(obj) {

   alert("Just added " + obj.name + ".");

} function coworker(name, age) {

   this.name = name;
   this.age = age;
   this.show = showAll;
   verify(this);

}


var employeeDB = new Array(); employeeDB[employeeDB.length] = new coworker("Alice", 23); employeeDB[employeeDB.length] = new coworker("Fred", 32); employeeDB[employeeDB.length] = new coworker("Jean", 28); employeeDB[employeeDB.length] = new coworker("Steve", 24);


var employeeDB = new Array(); employeeDB[employeeDB.length] = {name:"Alice", age:23, show:showAll}; employeeDB[employeeDB.length] = {name:"Fred", age:32, show:showAll}; employeeDB[employeeDB.length] = {name:"Jean", age:28, show:showAll}; employeeDB[employeeDB.length] = {name:"Steve", age:24, show:showAll};


var employeeDB = [{name:"Alice", age:23, show:showAll},

                 {name:"Fred", age:32, show:showAll},
                 {name:"Jean", age:28, show:showAll},
                 {name:"Steve", age:24, show:showAll}];

function findInAgeGroup(low, high) {

   var result = new Array();
   for (var i = 0; i < employeeDB.length; i++) {
       if (employeeDB[i].age >= low && employeeDB[i].age <= high) {
           result = result.concat(employeeDB[i].name);
       }
   }
   return result;

}


 </source>
   
  


Define Object, use its instance

   <source lang="html4strict">

<HTML> <HEAD> <SCRIPT language="JavaScript">

</SCRIPT> </HEAD> <BODY> <SCRIPT language="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Display the properties from an object one by one

   <source lang="html4strict">

<head> <title></title> </script> </head> <body> <script type = "text/javascript" >

   function MyClass(a,b,c,d) {
       this.a = a;
       this.b = b;
       this.c = c;
       this.d = d;
   }
   var MyClass = {};
   MyClass["item1"] = new MyClass("A","B","F",2.0);

for (var propt in MyClass) {

   document.write( propt );
   document.write("
");

}

var names = new Array; for (propt in MyClass) {

   if (names != "") {
       names += "," + propt;
   } else {
       names = propt;
   }

} document.write(names); </script>

MyClasss

</body>

 </source>
   
  


Object-Oriented Planetary Data Presentation

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Our Solar System</TITLE> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> <BODY>

The Daily Planet


<FORM>

Select a planet to view its planetary data: <SELECT NAME="planetsList" onChange="doDisplay(this)"> <OPTION>Mercury <OPTION>Venus <OPTION SELECTED>Earth <OPTION>Mars <OPTION>Jupiter <OPTION>Saturn <OPTION>Uranus <OPTION>Neptune <OPTION>Pluto </SELECT>

</FORM> </BODY> </HTML>


 </source>
   
  


Object to array

   <source lang="html4strict">

/* objectsArraysStrings.js */ /*

    Example File From "JavaScript and DHTML Cookbook"
    Published by O"Reilly & Associates
    Copyright 2003 Danny Goodman
  • /

function object2String(obj) {

   var val, output = "";
   if (obj) {    
       output += "{";
       for (var i in obj) {
           val = obj[i];
           switch (typeof val) {
               case ("object"):
                   if (val[0]) {
                       output += i + ":" + array2String(val) + ",";
                   } else {
                       output += i + ":" + object2String(val) + ",";
                   }
                   break;
               case ("string"):
                   output += i + ":"" + escape(val) + "",";
                   break;
               default:
                   output += i + ":" + val + ",";
           }
       }
       output = output.substring(0, output.length-1) + "}";
   }
   return output;

} function array2String(array) {

   var output = "";
   if (array) {
       output += "[";
       for (var i in array) {
           val = array[i];
           switch (typeof val) {
               case ("object"):
                   if (val[0]) {
                       output += array2String(val) + ",";
                   } else {
                       output += object2String(val) + ",";
                   }
                   break;
               case ("string"):
                   output += """ + escape(val) + "",";
                   break;
               default:
                   output += val + ",";
           }
       }
       output = output.substring(0, output.length-1) + "]";
   }
   return output;

}

function string2Object(string) {

   eval("var result = " + string);
   return result;

} function string2Array(string) {

   eval("var result = " + string);
   return result;

}


 </source>
   
  


Object utility: create, parse and profile

   <source lang="html4strict">


/* JavaScript Application Cookbook By Jerry Bradenbaugh Publisher: O"Reilly Series: Cookbooks ISBN: 1-56592-577-7

  • /

<HTML> <HEAD> <TITLE>objects.js Example</TITLE> <STYLE type="text/css">

</STYLE> <SCRIPT LANGUAGE="JavaScript"> // objects.js // This function creates new objects function makeObj() {

 if (arguments.length % 2 != 0) {
   arguments[arguments.length] = "";
   }
 for ( var i = 0; i < arguments.length; i += 2 ) {
   this[arguments[i]] = arguments[i + 1] ;
    }
 return this;
 }

// This function recursively inspects passed objects // and stores property information in a string. This string is // returned after there are no more object properties to examine function parseObj(obj) {

 objCount = 0;
 var objStr = "";
   for (prop in obj) {
     objStr += "<TR><TD>Property: </TD><TD>" + prop + "</TD><TD>Type: </TD><TD>" + typeof(obj[prop]) + 
       "</TD><TD>Value: </TD><TD>"  + obj[prop] + "</TD></TR>";
     if (typeof(obj[prop]) == "object") {
       objStr += parseObj(obj[prop]);
       }
     }
 return objStr;
 }

// This function displays object properties accumulated from parseObj() function objProfile() {

var objTable = "";
 for (var i = 0; i < arguments.length; i++) { 
objTable += "

Object Profile



" + (i + 1) + ") " + arguments[i] + "</H2></TD></TR>"; objTable += "

<TT>" + parseObj(eval(arguments[i])) + "
</TD></TR>";
   }
 objTable += "</TABLE>


"; return objTable; }

</SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Source Code for the showBook() Example

   <source lang="html4strict">

<html> <head>

 <title>Using the book object</title>
 <script type="text/javascript">
 
 </script>

</head><body>

Book Objects

 <form name="form1">

Select a book:

<select name="bookList" size=1> <option value="dbBook">A</option> <option value="fkBook">B</option> <option value="olBook">C</option> <option value="iaBook">D</option> <option value="cnBook">E</option> </select>

Assign a rating:

<select name="rating" size=1> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select>

Click to assign:

<input type="button" name="Assign" value="Assign" onClick="assignRating()">

Click to show:

<input type="button" name="Show" value="Show" onClick="showBook()">

 </form></body>
  

</html>


 </source>
   
  


The Book Object Definition

   <source lang="html4strict">

<script type="text/javascript">

</script>


 </source>
   
  


Use for in loop to display all attributes from an object

   <source lang="html4strict">

<html> <head>

   <title>For In Loop Example</title>

</head> <body> <script type = "text/javascript">

   var aObject = new Object;
   
   aObject.name = "A";
   aObject.type = "b";
   aObject.myValue = "c";
   
   for (var obj in aObject) {
       document.write(obj + " = " + aObject[obj]+"
"); }

</script>

</body> </html>

 </source>
   
  


Use function as the object constructor

   <source lang="html4strict">

<head> <title></title> </script> </head> <body> <script type = "text/javascript" > function Song(artist,length,title) {

   this.artist = artist;
   this.length = length;
   this.title = title;

} song1 = new Song("A","3:30","title"); </script>

Songs

</body>

 </source>
   
  


Using the Book Object Constructor

   <source lang="html4strict">

<html> <head>

 <title>Using the book object</title>
 <script type="text/javascript">
   </script>

</head> <body>

 <script type="text/javascript">
 
 </script>

</body> </html>


 </source>
   
  


Utility class for JavaScript class definition

<A href="http://www.wbex.ru/Code/JavaScriptDownload/JSClass.zip">JSClass.zip( 23 k)</a>

1. <A href="/Code/JavaScript/Language-Basics/Objectutilitycreateparseandprofile.htm">Object utility: create, parse and profile</a> 2. <A href="/Code/JavaScript/Language-Basics/DefineObjectuseitsinstance.htm">Define Object, use its instance</a> 3. <A href="/Code/JavaScript/Language-Basics/Defineanduseobject.htm">Define and use object</a> 4. <A href="/Code/JavaScript/Language-Basics/CreatinganObjectandUsingObjectInstancePropertiesandMethods.htm"> Creating an Object and Using Object Instance Properties and Methods</a> 5. <A href="/Code/JavaScript/Language-Basics/ObjectOrientedPlanetaryDataPresentation.htm"> Object-Oriented Planetary Data Presentation</a> 6. <A href="/Code/JavaScript/Language-Basics/TheBookObjectDefinition.htm">The Book Object Definition</a> 7. <A href="/Code/JavaScript/Language-Basics/CompleteExampleofUsingtheemployeeclientandprojectObjects.htm">Complete Example of Using the employee, client, and project Objects</a> 8. <A href="/Code/JavaScript/Language-Basics/SourceCodefortheshowBookExample.htm">Source Code for the showBook() Example</a> 9. <A href="/Code/JavaScript/Language-Basics/UsingtheBookObjectConstructor.htm">Using the Book Object Constructor</a> 10. <A href="/Code/JavaScript/Language-Basics/CreatingObjectsDynamically.htm">Creating Objects Dynamically</a> 11. <A href="/Code/JavaScript/Language-Basics/Objecttoarray.htm">Object to array</a> 12. <A href="/Code/JavaScript/Language-Basics/Createanobjectandaddattributes.htm">Create an object and add attributes</a> 13. <A href="/Code/JavaScript/Language-Basics/Useforinlooptodisplayallattributesfromanobject.htm">Use for in loop to display all attributes from an object</a> 14. <A href="/Code/JavaScript/Language-Basics/Displaythepropertiesfromanobjectonebyone.htm">Display the properties from an object one by one</a> 15. <A href="/Code/JavaScript/Language-Basics/Anobjectanditsconstructor.htm">An object and its constructor</a> 16. <A href="/Code/JavaScript/Language-Basics/Usefunctionastheobjectconstructor.htm">Use function as the object constructor</a>