JavaScript Objects and Functions
JavaScript Objects and Functions
The Constructors of an Object
Introduction
As mentioned for classes in C#, a constructor is a method that is used to create an object of a class. The objects of JavaScript also support constructors in various ways.
Practical Learning: Introducing Functions
body { background-color: white; } form { padding: 1em; background-color: #e0d4c0; border: 1px solid maroon; } form div { padding: 4px; margin: 0 0 1px 0; } input[type=number] { width: 80px; float: right; border: 1px solid maroon; } input[type=number]:focus { outline: 1px solid #ff6a00; } input[type=button] { border: 0; border-radius: 10px; font-size: 14px; width: 130px; margin-left: 100px; background-color: brown; padding: 0.75em; color: yellow; } input[type=button]:hover { color: white; cursor: pointer; background-color: chocolate; } form > fieldset > div > div { margin: 0 0 5px 0 } .container h1 { margin: auto; width: 600px; } .container form { margin: auto; width: 280px; } .centered { text-align: center; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>ESCAPE - Bill Evaluation</title> <link rel="stylesheet" type="text/css" href="CableCompany.css" /> </head> <body> <div class="container"> <h1 class="centered">ESCAPE</h1> <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2> <h3 class="centered">Bill Evaluation</h3> </div> <div class="container"> <form name="BillEvaluation" method="post"> <fieldset> <legend>Cable TV Services</legend> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <input type="number" id="CableTVBasicFee" name="CableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <input type="number" id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="SportPackage">Sport Package:</label> <input type="number" id="SportsPackage" name="SportsPackage" value="0.00" /> </div> <div> <label for="subTotal">Sub-Total:</label> <input type="number" id="subTotal" name="subTotal" value="0.00" /> </div> <div> <label for="countyTaxes">County Taxes:</label> <input type="number" id="countyTaxes" name="countyTaxes" value="0.00" /> </div> </fieldset> </form> </div> <script> var bill = this; this.basicFee = 44.68; this.dvr = 11.96; this.sports = 12.85; bill.subTotal = function () { return bill.basicFee + this.dvr + this.sports; }; bill.localTaxes = function (rate) { return bill.subTotal() * rate / 100; }; document.BillEvaluation.CableTVBasicFee.value = this.basicFee; document.BillEvaluation.DVRService.value = this.dvr; document.BillEvaluation.SportsPackage.value = this.sports; document.BillEvaluation.subTotal.value = this.subTotal(); document.BillEvaluation.countyTaxes.value = this.localTaxes(0.15); </script> </body> </html>
An Anonymous Constructor
To create an object, you can start by defining an anonymous function and assign it to a variable. Here is an example:
var bill = function () { };
In the body of the function, create the members of the object. Each member must be created using eiher the name of the variable, which becomes an object, or the this object. Here is an example that uses the name of the variable:
var bill = function () { bill.basicFee = 45.05; bill.dvr = 9.95; bill.sports = 12.45; };
If you use the name of the object to create the member(s), you can use the same name outside the class to access the members, but you must first call the variable as a function. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>SCAPE - Bill Evaluation</title> <link rel="stylesheet" type="text/css" href="CableCompany.css" /> </head> <body> <div class="container"> <h1 class="centered">ESCAPE</h1> <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2> <h3 class="centered">Bill Evaluation</h3> </div> <div class="container"> <form name="BillEvaluation" method="post"> <fieldset> <legend>Cable TV Services</legend> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <input type="number" id="CableTVBasicFee" name="CableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <input type="number" id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="SportPackage">Sport Package:</label> <input type="number" id="SportsPackage" name="SportsPackage" value="0.00" /> </div> </fieldset> </form> </div> <script> var bill = function () { bill.basicFee = 18.86; bill.dvr = 4.88; bill.sports = 8.58; }; bill(); document.BillEvaluation.CableTVBasicFee.value = bill.basicFee; document.BillEvaluation.DVRService.value = bill.dvr; document.BillEvaluation.SportsPackage.value = bill.sports; </script> </body> </html>
This would produce:
As mentioned previously, you can also attach the members using the this object. Once again, before accessing the members outside the object, you must call the varable as a function. This time, to access a member of the object, use the this object. Here are examples:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>SCAPE - Bill Evaluation</title> <link rel="stylesheet" type="text/css" href="CableCompany.css" /> </head> <body> <div class="container"> <h1 class="centered">ESCAPE</h1> <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2> <h3 class="centered">Bill Evaluation</h3> </div> <div class="container"> <form name="BillEvaluation" method="post"> <fieldset> <legend>Cable TV Services</legend> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <input type="number" id="CableTVBasicFee" name="CableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <input type="number" id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="SportPackage">Sport Package:</label> <input type="number" id="SportsPackage" name="SportsPackage" value="0.00" /> </div> </fieldset> </form> </div> <script> var bill = function () { this.basicFee = 45.05; this.dvr = 9.95; this.sports = 12.45; }; bill(); document.BillEvaluation.CableTVBasicFee.value = this.basicFee; document.BillEvaluation.DVRService.value = this.dvr; document.BillEvaluation.SportsPackage.value = this.sports; </script> </body> </html> }
A Named Constructor
As one way to get a constructor, create a regular function. Define an object in it. Before the end of the function, you must return the object you had created. Here is an example:
function create() { var bill = {}; bill.basicFee = 32.70; bill.dvr = 10.45; bill.sports = 12.20; bill.total = function () { return this.basicFee + this.dvr + this.sports; }; bill.localTaxes = function (rate) { var taxes = this.total() * rate / 100; return taxes; } return bill; };
To access the object outside the function, you can first declare a variable and assign a call of the funtion to it. To access a member of the class, type the name of the variable, a period, and the desired member.
Practical Learning: Creating a Constructor
<!DOCTYPE html> <html> <head> <title>ESCAPE - Bill Evaluation</title> <link rel="stylesheet" type="text/css" href="~/CableCompany.css" /> </head> <body> <div class="container"> <h1 class="centered">ESCAPE</h1> <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2> <h3 class="centered">Bill Evaluation</h3> </div> <div class="container"> <form name="BillEvaluation" method="post"> <fieldset> <legend>Cable TV Services</legend> <div> <label for="cableTVBasicFee">Cable TV Basic Fee:</label> <input type="number" id="cableTVBasicFee" name="cableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <input type="number" id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="sportPackage">Sport Package:</label> <input type="number" id="sportsPackage" name="sportsPackage" value="0.00" /> </div> <div> <label for="subTotal">Sub-Total:</label> <input type="number" id="subTotal" name="subTotal" value="0.00" /> </div> <div> <label for="countyTaxes">County Taxes:</label> <input type="number" id="countyTaxes" name="countyTaxes" value="0.00" /> </div> <div> <label for="stateTaxes">State Taxes:</label> <input type="number" id="stateTaxes" name="stateTaxes" value="0.00" /> </div> <div> <label for="paymentAmount">Payment Amount:</label> <input type="number" id="paymentAmount" name="paymentAmount" value="0.00" /> </div> </fieldset> </form> </div> <script> function create() { var bill = {}; bill.basicFee = 22.95; bill.dvr = 12.25; bill.sports = 11.85; bill.subTotal = function () { return this.basicFee + this.dvr + this.sports; }; bill.calcTaxes = function (rate) { return this.subTotal() * rate / 100; } return bill; }; var pay = create(); var total = pay.subTotal(); var local = pay.calcTaxes(0.15); var state = pay.calcTaxes(0.05); document.BillEvaluation.cableTVBasicFee.value = pay.basicFee; document.BillEvaluation.DVRService.value = pay.dvr; document.BillEvaluation.sportsPackage.value = pay.sports; document.BillEvaluation.subTotal.value = pay.subTotal(); document.BillEvaluation.countyTaxes.value = local; document.BillEvaluation.stateTaxes.value = state; document.BillEvaluation.paymentAmount.value = total + local + state; </script> </body> </html>
A Constructor with Parameters
When creating a function that acts as a constructor, you can give one or more parameters. Once again, in the body of the constructor, you can use or ignore the parameter(s). Usually, you provide a parameter so you can use it in the constructor, in which case you would assign the parameter(s) to a property (or some properties) of the object. Of course, when calling the function, you must pass the arguments.
Practical Learning: Passing Arguments to a Constructor
<!DOCTYPE html> <html> <head> <title>ESCAPE - Bill Evaluation</title> <link rel="stylesheet" type="text/css" href="~/CableCompany.css" /> </head> <body> <div class="container"> <h1 class="centered">ESCAPE</h1> <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2> <h3 class="centered">Bill Evaluation</h3> </div> <div class="container"> <form name="BillEvaluation" method="post"> <fieldset> <legend>Cable TV Services</legend> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <input type="number" id="cableTVBasicFee" name="cableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <input type="number" id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="SportsPackage">Sports Package:</label> <input type="number" id="SportsPackage" name="SportsPackage" value="0.00" /> </div> <div> <label for="fccFee">FCC Fee:</label> <input type="number" id="fccFee" name="fccFee" value="0.00" /> </div> <div> <label for="subTotal">Sub-Total:</label> <input type="number" id="subTotal" name="subTotal" value="0.00" /> </div> <div> <label for="countyTaxes">County Taxes:</label> <input type="number" id="countyTaxes" name="countyTaxes" value="0.00" /> </div> <div> <label for="stateTaxes">State Taxes:</label> <input type="number" id="stateTaxes" name="stateTaxes" value="0.00" /> </div> <div> <label for="paymentAmount">Payment Amount:</label> <input type="number" id="paymentAmount" name="paymentAmount" value="0.00" /> </div> </fieldset> </form> </div> <script> function create(start, rent, plays) { var bill = {}; bill.basicFee = start; bill.dvr = rent; bill.sports = plays; bill.fccFee = 1.05; bill.subTotal = function () { return this.basicFee + this.dvr + this.sports + this.fccFee; }; bill.calcTaxes = function (rate) { return taxes = this.subTotal() * rate / 100; } return bill; }; var pay = create(28.85, 8.88, 7.95); var local = pay.calcTaxes(0.15); var state = pay.calcTaxes(0.05); document.BillEvaluation.cableTVBasicFee.value = pay.basicFee; document.BillEvaluation.DVRService.value = pay.dvr; document.BillEvaluation.sportsPackage.value = pay.sports; document.BillEvaluation.fccFee.value = pay.fccFee; document.BillEvaluation.subTotal.value = pay.pay.subTotal()(); document.BillEvaluation.countyTaxes.value = local; document.BillEvaluation.stateTaxes.value = state; document.BillEvaluation.paymentAmount.value = subTotal + local + state; </script> </body> </html>
function create(start, rent, plays) { var bill = {}; bill.basicFee = start; bill.dvr = rent; bill.sports = plays; bill.fccFee = 1.05; bill.subTotal = function () { return this.basicFee + this.dvr + this.sports + this.fccFee; }; bill.calcTaxes = function (rate) { return this.subTotal() * rate / 100; } return bill; };
A Constructor to Create a New Object
You can create a new function and create an object at the same time. To do this, create the function as we have done so far. Here is an example:
function Customer() { };
In the body of the function, you must create the members of the object. Each member must be preceded by this. followed by the name of the member. If the member is a property, you can assign the desired value to it. Here is an example:
function Customer() {
this.accountNumber = '408-2057-81';
};
In the same way, you can create as many members as you want, including properties and methods. If you want, you can add a parameter to the function. You can then assign such a parameter to a property. Here is an example:
function Customer(antNbr) { this.accountNumber = antNbr; };
In the same way, you can give as many parameters as you want to the constructor.
Practical Learning: Creating an Object Through a Constructor
function Customer(acntNbr, first, last, adrs) { this.AccountNumber = acntNbr; this.FirstName = first; this.LastName = last; this.Address = adrs; this.FullName = function () { return this.LastName + ', ' + this.FirstName; } };
<!DOCTYPE html> <html> <head> <title>ESCAPE - Bill Evaluation</title> <script src="~/Customer.js"></script> <script src="~/WaterBill.js"></script> <link rel="stylesheet" type="text/css" href="~/CableCompany.css" /> </head> <body> <div class="container"> <h1 class="centered">ESCAPE</h1> <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2> <h3 class="centered">Bill Evaluation</h3> </div> <div class="container"> <form name="BillEvaluation" method="post"> <fieldset> <legend>Customer Information</legend> <div> <label for="accountNumber">Account #:</label> <input type="text" id="accountNumber" name="accountNumber" /> </div> <div> <label for="customerName">Full Name:</label> <input type="text" id="customerName" name="customerName" /> </div> </fieldset> <hr /> <fieldset> <legend>Cable TV Services</legend> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <input type="number" id="CableTVBasicFee" name="CableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <input type="number" id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="SportsPackage">Sport Package:</label> <input type="number" id="SportsPackage" name="SportsPackage" value="0.00" /> </div> <div> <label for="fccFee">FCC Fee:</label> <input type="number" id="fccFee" name="fccFee" value="0.00" /> </div> <div> <label for="subTotal">Sub-Total:</label> <input type="number" id="subTotal" name="subTotal" value="0.00" /> </div> <div> <label for="countyTaxes">County Taxes:</label> <input type="number" id="countyTaxes" name="countyTaxes" value="0.00" /> </div> <div> <label for="stateTaxes">State Taxes:</label> <input type="number" id="stateTaxes" name="stateTaxes" value="0.00" /> </div> <div> <label for="paymentAmount">Payment Amount:</label> <input type="number" id="paymentAmount" name="paymentAmount" value="0.00" /> </div> </fieldset> </form> </div> <script> var pay = create(32.60, 9.95, 9.70); var client = new Customer('408-2057-81', 'Julius', 'Amadeo', '8725 Henrietta Road'); var local = pay.calcTaxes(0.15); var state = pay.calcTaxes(0.05); document.BillEvaluation.CableTVBasicFee.value = pay.basicFee; document.BillEvaluation.DVRService.value = pay.dvr; document.BillEvaluation.SportsPackage.value = pay.sports; document.BillEvaluation.fccFee.value = pay.fccFee; document.BillEvaluation.subTotal.value = pay.subTotal(); document.BillEvaluation.countyTaxes.value = local; document.BillEvaluation.stateTaxes.value = state; document.BillEvaluation.paymentAmount.value = pay.subTotal() + local + state; document.BillEvaluation.accountNumber.value = client.AccountNumber; document.BillEvaluation.customerName.value = client.FullName(); </script> </body> </html>
Functions and Objects
An Object in a Function
In JavaScript, you can create anything, such as an object, in the body of a function. To create an object in a function, assign a name to the var keyword and add the members as we have learned already. Here is an example:
function evaluatePayment() {
var basicFee = 24.95;
var discountRate = 20;
var customer = {
firstName : "Samuel",
lastName : "Clarington",
address : "1806 Bakken Drive",
city : "Rockville",
county : "Montgomery",
state: "MD"
};
var amountOwed = 0.00;
}
In the body of the function, to access a member of the object, type the object name, a period, and the intended member. Here are examples:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>ESCAPE: Bill Evaluation</title> <link rel="stylesheet" type="text/css" href="CableCompany.css" /> </head> <body> <div class="container"> <h1 class="centered">ESCAPE</h1> <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2> <h3 class="centered">Bill Evaluation</h3> </div> <div class="container"> <form name="BillEvaluation" method="post"> <fieldset> <legend>Cable TV Services</legend> <fieldset> <legend>Customer Information</legend> <div> <label for="accountNumber">Account #:</label> <input type="text" id="accountNumber" name="accountNumber" /> </div> <div> <label for="customerName">Full Name:</label> <input type="text" id="customerName" name="customerName" /> </div> </fieldset> <hr /> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <input type="number" id="CableTVBasicFee" name="CableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <input type="number" id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="SportsPackage">Sports Package:</label> <input type="number" id="SportsPackage" name="SportsPackage" value="0.00" /> </div> <div> <div> <input type="button" name="btnEvaluate" value="Evaluate" onclick="evaluatePayment()" /> </div> </div> <div> <label for="PaymentAmount">Payment Amount:</label> <input type="number" id="PaymentAmount" name="PaymentAmount" value="0.00" /> </div> </fieldset> </form> </div> <script> function evaluatePayment() { 'use strict'; var basicFee = 24.95; var dvr = 9.90; var sport = 8.90; var amount = basicFee + dvr + sport; var customer = { accountNumber : 284705, firstName : "Samuel", lastName : "Clarington", address : "1806 Bakken Drive", city : "Rockville", county : "Montgomery", state: "MD" }; var amount = basicFee + dvr + sport; document.BillEvaluation.CableTVBasicFee.value = basicFee; document.BillEvaluation.DVRService.value = dvr; document.BillEvaluation.SportsPackage.value = sport; document.BillEvaluation.PaymentAmount.value = amount; document.BillEvaluation.customerName.value = customer.firstName + ' ' + customer.lastName; document.BillEvaluation.accountNumber.value = customer.accountNumber; } </script> </body> </html>
Returning an Object
You can create a function that produces an object. The classic way is to create an object in the function and, before the closing curly bracket, use the return to return the object. Here is an example:
function create() { var toy = { itemNumber: 937495, toyName: "Mini Point of Sale Station", unitPrice: 32.64 }; return toy; }
To use the object, you can first declare a variable and assign the fuction call to it. That variable would then have the properties of the object and their values. You can then use that variable as it were the original object. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Children Toy Store</title> </head> <body> <h1>Children Toy Store</h1> <form name="ToyStore" method="post"> <table> <tr> <td><b>Item #:</b></td> <td><input type="text" name="itemNumber" /></td> </tr> <tr> <td><b>Toy Name:</b></td> <td><input type="text" name="toyName" style="width: 200px" /></td> </tr> <tr> <td><b>Price:</b></td> <td><input type="number" name="price" /></td> </tr> </table> </form> <script type="text/javascript"> var mpss = create(); document.ToyStore.itemNumber.value = mpss.itemNumber; document.ToyStore.toyName.value = mpss.toyName; document.ToyStore.price.value = mpss.unitPrice; function create() { var toy = { itemNumber: 937495, toyName: "Mini Point of Sale Station", unitPrice: 32.64 }; return toy; } </script> </body> </html>
In the above code, before returning an object, we first declared a variable and assigned the object to it. This is useful if you plan to do something on the object before returning it. Here is an example:
. . . No Change
<script type="text/javascript">
var mpss = create();
document.ToyStore.itemNumber.value = mpss.itemNumber;
document.ToyStore.toyName.value = mpss.toyName;
document.ToyStore.price.value = mpss.unitPrice;
function create() {
var toy = {
itemNumber: 937495,
toyName: "Mini Point of Sale Station",
unitPrice: 32.64
};
toy.unitPrice = 27.38;
return toy;
}
</script>
</body>
</html>
If you are not planing to modify an object you want to produce, you can create it directly after the return keywork. Here is an example:
. . . Change
<script type="text/javascript">
var mpss = create();
document.ToyStore.itemNumber.value = mpss.itemNumber;
document.ToyStore.toyName.value = mpss.toyName;
document.ToyStore.price.value = mpss.unitPrice;
function create() {
return {
itemNumber: 309581,
toyName: "Drawing Black Board",
unitPrice: 18.45
};
}
</script>
</body>
</html>
Passing an Object as Argument
You can pass an object as argument to a function. When creating the function, simply provide a name for the argument in the parentheses of the function. In the body of the function, (ignore or) use the object as you want. Access the members of the object normally. When calling the function, pass an appropriate object to it. Here is an example:
. . . No Change <script type="text/javascript"> function prepare(play) { document.ToyStore.itemNumber.value = play.itemNumber; document.ToyStore.toyName.value = play.toyName; document.ToyStore.price.value = play.unitPrice; } var mpss = create(); prepare(mpss); function create() { return { itemNumber: 749374, toyName: "Kid Ferry Boat", unitPrice: 24.86 }; } </script> </body> </html>
In the above code, we first define an object before passing its name to the function. Once again, you first define an object if you are planning to perform some operations on it before passing it to a function. If you have a constant object you want to pass to a function, you can create it directly in the parentheses of the function call. Here is an example:
. . . No Change
<script type="text/javascript">
function prepare(play) {
document.ToyStore.itemNumber.value = play.itemNumber;
document.ToyStore.toyName.value = play.toyName;
document.ToyStore.price.value = play.unitPrice;
}
prepare({
itemNumber: 583049,
toyName: "Easter Egg Decorating Set",
unitPrice: 32.04
});
</script>
</body>
</html>
JavaScript Libraries and Objects
Both the AngularJS and the jQuery libraries support objects, including all of the characteristics of objects such as methods, constructors, arguments, and the this object, exactly as they are used in JavaScript as we saw in the previous and this lesson.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|