JavaScript DHTML/Language Basics/Objects Object Oriented
Содержание
- 1 An object and its constructor
- 2 Complete Example of Using the employee, client, and project Objects
- 3 Create an object and add attributes
- 4 Creating an Object and Using Object Instance Properties and Methods
- 5 Creating Objects Dynamically
- 6 Define and use object
- 7 Define Object, use its instance
- 8 Display the properties from an object one by one
- 9 Object-Oriented Planetary Data Presentation
- 10 Object to array
- 11 Object utility: create, parse and profile
- 12 Source Code for the showBook() Example
- 13 The Book Object Definition
- 14 Use for in loop to display all attributes from an object
- 15 Use function as the object constructor
- 16 Using the Book Object Constructor
- 17 Utility class for JavaScript class definition
An object and its constructor
<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+"<BR>");
}
</script>
</body>
</html>
Complete Example of Using the employee, client, and project Objects
<html>
<head>
<title>Using the book object</title>
<script type="text/javascript">
<!--
function employee(FirstName, LastName, HomePhone, Ext, EmailAddress, project) {
this.FirstName = FirstName;
this.LastName = LastName;
this.HomePhone = HomePhone;
this.Ext = Ext;
this.EmailAddress = EmailAddress;
this.Project = project;
this.showSummaryInfo = summaryInfo;
}
function summaryInfo() {
objWindow = window.open("", "", "width=600,height=400");
objWindow.document.write("<html><body>");
objWindow.document.write("<h1>Employee Summary Information Sheet</h1>");
objWindow.document.write("<h2>" + this.FirstName + " " + this.LastName
+ "</h2>");
objWindow.document.write("<p><em><Sstrong>Contact Information</strong></em></p>");
objWindow.document.write("<p>Home Phone: " + this.HomePhone + "</p>");
objWindow.document.write("<p>Ext.: " + this.Ext + "</p>");
objWindow.document.write("<p>Email: " + this.EmailAddress + "</p>");
objWindow.document.write("<p><em><strong>Project Information</strong></em></p>");
objWindow.document.write("<p>Current Project: " + this.project.ProjectName+ "</p>");
objWindow.document.write("<p>Client: " + this.Project.Client.ClientName + "</p>");
objWindow.document.write("<p>Client: " + this.Project.Client.Address + "</p>");
objWindow.document.write("<p>Client: " + this.Project.Client.City + ", " +
this.Project.Client.State + " " + this.Project.Client.Zip + "</p>"); objWindow.document.write("<p>Development Tool Used: " + this.Project.DevTool
+ "</p>");
objWindow.document.write("</body></html>");
objWindow.document.close();
}
function project(ProjectName, client, DevTool) {
this.ProjectName = ProjectName;
this.Client = client;
this.DevTool = DevTool;
}
function client(ClientName, Address, City, State, Zip) {
this.ClientName = ClientName;
this.Address = Address;
this.City = City;
this.State = State;
this.Zip = Zip;
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
CoastTech = new client("client Name", "100 street", "City","State", "11111");
Coastal = new project("projectl01", CoastTech, "JavaScript");
Allen = new employee("A", "B", "111/555-1111", "100","a@a.ru", "Coastal");
Allen.showSummaryInfo();
//-->
</script>
</body>
</html>
Create an object and add attributes
<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>
Creating an Object and Using Object Instance Properties and Methods
/*
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>
<H1>
<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 + "<br>");
document.write("The rectangle instance width is: " + theRectangle.width + "<br>");
document.write ("The calcArea method returns: " + theRectangle.calcArea());
</SCRIPT>
</H1>
</BODY>
</HTML>
Creating Objects Dynamically
<html>
<head>
<title>Student Database</title>
<script type="text/javascript">
<!--
var i = 0;
// Create Array objects
var empList = new Array();
// Student object constructor
function Student(FirstName, LastName, HomePhone, Ext, EmailAddress) {
this.FirstName = FirstName;
this.LastName = LastName;
this.HomePhone = HomePhone;
this.Ext = Ext;
this.EmailAddress = EmailAddress;
this.show = show;
}
function show() {
alert(this.FirstName + ":" +this.LastName + ":" +this.HomePhone + ":" +this.Ext + ":" + this.EmailAddress);
}
function addStudentObject(FirstName, LastName, HomePhone, Ext,EmailAddress) {
empList[i] = new Student(FirstName, LastName, HomePhone, Ext,EmailAddress);
}
function insertRecord() {
FirstName = document.form1.FirstName.value;
LastName = document.form1.LastName.value;
HomePhone = document.form1.HomePhone.value;
Ext = document.form1.Ext.value;
EmailAddress = document.form1.EmailAddress.value;
i++;
addStudentObject(FirstName, LastName, HomePhone, Ext, EmailAddress);
}
function showAll() {
for (var q=1; q<empList.length; q++) {
empList[q].show();
}
}
//-->
</script></head>
<body>
<h1>Dyanamic Object Creator</h1>
<form name="form1">
<pre>
First Name:
<input type=text size=20 maxlength=256 name="FirstName">
</pre>
<pre>
Last Name:
<input type=text size=20 maxlength=256 name="LastName">
</pre>
<pre>
Home Phone:
<input type=text size=20 maxlength=256 name="HomePhone">
</pre>
<pre>
Ext.:
<input type=text size=20 maxlength=256 name="Ext">
</pre>
<pre>
Email Address:
<input type=text size=20 maxlength=256 name="EmailAddress">
</pre>
<pre>
<input type="button" name="Add" value="Add" onClick="insertRecord()">
<input type="button" name="ShowAll" value="Show All"
onClick="showAll()">
</pre>
</form>
</body>
</html>
Define and use object
<!--
Example File From "JavaScript and DHTML Cookbook"
Published by O"Reilly & Associates
Copyright 2003 Danny Goodman
-->
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;
}
Define Object, use its instance
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
function get_price(){
var the_price=1000;
return the_price;
}
function computer(speed,hdspace,ram){
this.speed=speed;
this.hdspace=hdspace;
this.ram=ram;
this.price=get_price;
}
var pc1= new computer("500mHz","15GB","128MB");
var pc2= new computer("450mHz","10GB","64MB");
var pc3= new computer("350mHz","7GB","32MB");
var pc1_price= pc1.price();
var pc2_price= pc2.price();
var pc3_price= pc3.price();
//-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT language="JavaScript">
<!--
alert(pc1.hdspace+","+pc1.ram +","+pc1_price);
alert(pc2.speed+","+pc2.hdspace+","+pc2.ram+","+pc2_price);
alert(pc3.speed+","+pc3.hdspace+","+pc3.ram+","+pc3_price);
//-->
</SCRIPT>
</BODY>
</HTML>
Display the properties from an object one by one
<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("<BR>");
}
var names = new Array;
for (propt in MyClass) {
if (names != "") {
names += "," + propt;
} else {
names = propt;
}
}
document.write(names);
</script>
<p>MyClasss</p>
</body>
Object-Oriented Planetary Data Presentation
/*
JavaScript Bible, Fourth Edition
by Danny Goodman
John Wiley & Sons CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Our Solar System</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- start script
// method definition
function showPlanet() {
var result = "<HTML><BODY><CENTER><TABLE BORDER=2>"
result += "<CAPTION ALIGN=TOP>Planetary data for: <B>" + this.name + "</B></CAPTION>"
result += "<TR><TD ALIGN=RIGHT>Diameter:</TD><TD>" + this.diameter + "</TD></TR>"
result += "<TR><TD ALIGN=RIGHT>Distance from Sun:</TD><TD>" + this.distance + "</TD></TR>"
result += "<TR><TD ALIGN=RIGHT>One Orbit Around Sun:</TD><TD>" + this.year + "</TD></TR>"
result += "<TR><TD ALIGN=RIGHT>One Revolution (Earth Time):</TD><TD>" + this.day + "</TD></TR>"
result += "</TABLE></CENTER></BODY></HTML>"
// display results in a second frame of the window
document.write(result)
document.close()
}
// definition of planet object type;
// "new" will create a new instance and stuff parameter data into object
function planet(name, diameter, distance, year, day) {
this.name = name
this.diameter = diameter
this.distance = distance
this.year = year
this.day = day
this.showPlanet = showPlanet // make showPlanet() function a planet method
}
// create new planet objects, and store in a series of variables
var Mercury = new planet("Mercury","3100 miles", "36 million miles", "88 days",
"59 days")
var Venus = new planet("Venus", "7700 miles", "67 million miles", "225 days", "244 days")
var Earth = new planet("Earth", "7920 miles", "93 million miles", "365.25 days","24 hours")
var Mars = new planet("Mars", "4200 miles", "141 million miles", "687 days",
"24 hours, 24 minutes")
var Jupiter = new planet("Jupiter","88,640 miles","483 million miles",
"11.9 years", "9 hours, 50 minutes")
var Saturn = new planet("Saturn", "74,500 miles","886 million miles",
"29.5 years", "10 hours, 39 minutes")
var Uranus = new planet("Uranus", "32,000 miles","1.782 billion miles",
"84 years", "23 hours")
var Neptune = new planet("Neptune","31,000 miles","2.793 billion miles",
"165 years", "15 hours, 48 minutes")
var Pluto = new planet("Pluto", "1500 miles", "3.67 billion miles", "248 years", "6 days, 7 hours")
// called from push button to invoke planet object method
function doDisplay(popup) {
i = popup.selectedIndex
eval(popup.options[i].text + ".showPlanet()")
}
// end script -->
</SCRIPT>
<BODY>
<H1>The Daily Planet</H1>
<HR>
<FORM>
<P>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></P>
</FORM>
</BODY>
</HTML>
Object to array
<!--
Example File From "JavaScript and DHTML Cookbook"
Published by O"Reilly & Associates
Copyright 2003 Danny Goodman
-->
/* 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;
}
Object utility: create, parse and profile
/*
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">
<!--
td { font-family: courier new; font-size: 14}
-->
</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><B>" + prop + "</B></TD><TD>Type: </TD><TD><B>" + typeof(obj[prop]) +
"</B></TD><TD>Value: </TD><TD><B>" + obj[prop] + "</B></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 = "<TABLE BORDER=2 CELLSPACING=0><TR><TD><H1>Object Profile</H1></TD></TR>";
for (var i = 0; i < arguments.length; i++) {
objTable += "<TR><TD><BR><BR><H2><TT>" + (i + 1) + ") " + arguments[i] + "</H2></TD></TR>";
objTable += "<TR><TD><TT><TABLE CELLPADDING=5>" + parseObj(eval(arguments[i])) + "</TABLE></TD></TR>";
}
objTable += "</TABLE><BR><BR><BR>";
return objTable;
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
function plainOlderObject() {
this.stuff = "stuff";
this.that = "that";
this.theOther = "theOther";
return this;
}
function plainOldObject() {
this.name = "the object name";
this.numba = 1000;
this.objInherit = new makeObj("propertyOne", "thisProperty", "propertyTwo", "thatProperty", "propertyThree", "theOtherProperty");
return this;
}
var someObject = new plainOldObject();
document.write(objProfile("someObject", "self.location"));
//-->
</SCRIPT>
</BODY>
</HTML>
Source Code for the showBook() Example
<html>
<head>
<title>Using the book object</title>
<script type="text/javascript">
<!--
function book(title, author, ISBN, subject, rating) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.subject = subject;
this.rating = rating;
this.show = show;
}
function show() {
alert(this.title + " "+ this.author + " " + this.ISBN + " " + this.subject + " " + this.rating);
}
function assignRating() {
selectedBook = document.form1.bookList.options[document.form1.bookList.selectedIndex].value;
selectedBook = eval(selectedBook);
selectedBook.rating = document.form1.rating.options[document.form1.rating.selectedIndex].text;
}
function showBook() {
selectedBook = document.form1.bookList.options[document.form1.bookList.selectedIndex].value;
selectedBook = eval(selectedBook);
selectedBook.show();
}
// Execute on loading
dbBook = new book("A", "AA","1-11111-118-1", "A1", 5);
fkBook = new book("B", "BB","1-22222-112-1", "B1", 5);
olBook = new book("C", "CC","1-33333-118-1", "C1", 4);
iaBook = new book("D", "DD","1-44444-118-1", "D1", 3);
cnBook = new book("E", "EE","1-55555-128-1", "F1", 5);
//-->
</script>
</head><body>
<h1>Book Objects</h1>
<form name="form1">
<p>
Select a book:
</p>
<p>
<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>
</p>
<p>
Assign a rating:
</p>
<p>
<select name="rating" size=1>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</p>
<p>
Click to assign:
</p>
<p>
<input type="button" name="Assign" value="Assign" onClick="assignRating()">
</p>
<p>
Click to show:
</p>
<p>
<input type="button" name="Show" value="Show" onClick="showBook()">
</p>
</form></body>
</html>
The Book Object Definition
<script type="text/javascript">
<!--
function book(title, author, subject, rating) {
this.title = title;
this.author = author;
this.subject = subject;
this.rating = rating;
this.show = show;
}
function show() {
alert(this.title + this.author + this.subject + this.rating);
}
//-->
</script>
Use for in loop to display all attributes from an object
<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]+"<BR>");
}
</script>
</body>
</html>
Use function as the object constructor
<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>
<p>Songs</p>
</body>
Using the Book Object Constructor
<html>
<head>
<title>Using the book object</title>
<script type="text/javascript">
<!--
function book(title, author, ISBN, subject, rating) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.subject = subject;
this.rating = rating;
this.show = show;
}
function show() {
alert(this.title + this.author + this.ISBN + this.subject + this.rating );
}
//--> </script>
</head>
<body>
<script type="text/javascript">
<!--
dbBook = new book("Title", "Author","1-11111-111-1", "Computer", 5);
dbBook.show();
//-->
</script>
</body>
</html>
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>