Introduction to Objects
Introduction to Objects
Fundamentals of Objects
Object Definition
An object is a list of names and values that describe something. Each aspect of the object is specified as a combination of a name and a value.
Practical Learning: Introducing Functions
Creating an Object
There are various ways to create an object. One technique uses the following formula:
var | let object-name = {};
Based on this, start with the var or the let keyword followed by a name and assign {} to it. Since this is a statement, you should end it with a semicolon. Here is an example:
let storeItem = {};
In the same way, you can create as many objects as you want in your TypeScript file.
Practical Learning: Creating an Object
let fireTruck = {}; let buildingBlock = {};
Introduction to the Properties of an Object
A property is the combination of a name and a value that describes one detail about an object. The property must be created as a member of the object. Adding a property to an object is also referred to as attaching a property to an object.
To attach a property to an object, in the body of the object, a property is defined as follows:
var | let object-name = { property-definition };
The formula to create a property (property-definition in our formula) is:
property-name: value
Start by providing a name for the property, followed by a colon, and a value. If the value is a number, just type it. If the value is Boolean, specify it as true or false. If the value is symbol, a letter, a word, a sentence, or a combination of digits and letters, provide it in single or double-quotes.
The name of a property can be a letter. Here is an example:
let fireTruck = {
q: "Fire Truck with Remote Control"
};
In fact, the name can be any recognize ASCII symbol such as letter. Here is an example:
let alphabet = {
δ: 'Delta'
};
The name can also be a symbol. Here is an example:
let currency = { $: 'Dollar' };
The name can be a word, which is a combination of letters without a space. Here is an example:
let trafficTicket = { photoAvailable: true };
If you will access the name for a webpage, such as to display the value of the property, the name cannot be a number by itself. If you insist on using a number, start it with an underscore followed by digits only. In other words, you can use only a natural number. Here is an example:
let number = { _8: 88.888 };
An Object with many Properties
Most of the time, you need more than one piece of information to describe an object. As a result, you can create as many properties as you want in an object. Separate the properties with commas. The formula to follow is:
var | let object-name = { member_1, member_n, . . . member_n };
Here are examples:
let trafficTicket = { u: "Unknown Reason", $: 'Currency Accepted', photo: true, video: false, ticketMediaHaveBeenReviewed: false, ticketAmount: 125 };
Practical Learning: Attaching Properties to an Object
let fireTruck = {
name: "Fire Truck with Remote Control",
originalPrice: 15.50,
description: 'This toy is mostly made of plastic with an motor inside.',
requiresBatteries: true
};
let buildingBlock = {};
Accessing a Property of an Object
After attaching properties to an object, you can access those properties and use each as you see fit. To access a property, type the name of the object, a period, and the desired property. To display the value of a property in a webpage or view, you can use any of the techniques we saw for variables.
Practical Learning: Accessing the Properties of Objects
let fireTruck = { name: "Fire Truck with Remote Control", originalPrice: 15.50, description: 'This toy is mostly made of plastic with an motor inside.', requiresBatteries: true }; let buildingBlock = { price: 55.55, definition: '612 Pieces Building Kit', moreInformation: "The package contains different types and shapes of blocks that can be used to create various types of objects.", requiresBatteries: false }; document.querySelector(".toy1a").innerHTML = "<b>Toy Name:</b> " + fireTruck.name; document.querySelector("#toy1b").innerHTML = "<b>Price:</b> " + fireTruck.originalPrice; document.querySelector("#toy1c").innerHTML = "<b>Description:</b> " + fireTruck.description; document.querySelector("#toy1d").innerHTML = "<b>Description:</b> " + fireTruck.requiresBatteries;
using System.Web.Mvc;
namespace ToysStore1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult ToyPresentation() => View();
}
}
@{ ViewBag.Title = "Toy Inventory"; } <h2>Toy Inventory</h2> <hr /> <ul style="list-style-type: none"> <li class="toy1a"></li> <li id="toy1b"></li> <li id="toy1c"></li> <li id="toy1d"></li> </ul> <script src="~/Scripts/ToyExamination.js"></script>
Introduction to the Methods of an Object
Overview
In the body of an object, you can create a function. Such a function becomes a member of the object. A function member created in the body of an object is called a method.
Creating a Method
To attach a method to an object, in the body of the object, create a new property, followed by a colon, and define a function. The function doesn't need a name. Here is an example:
let fireTruck = {
name: "Fire Truck with Remote Control",
originalPrice: 15.50,
description: 'This toy is mostly made of plastic with an motor inside.',
summarize: function () {}
};
To access a member of the class in the method, precede it with the name of the object and a period. Here are examples:
let fireTruck = { name: "Fire Truck with Remote Control", originalPrice: 15.50, description: 'This toy is mostly made of plastic with an motor inside.', summarize: function () { document.querySelector(".toy1a").innerHTML = "<b>Toy Name:</b> " + fireTruck.name; document.querySelector("#toy1b").innerHTML = "<b>Price:</b> " + fireTruck.originalPrice; document.querySelector("#toy1c").innerHTML = "<b>Description:</b> " + fireTruck.description; } };
To call a method outside its parent object, type the name of the object, a period, the name of the method, and the parentheses. If this is the end of the statment, make sure to end it with a semicolon.
Practical Learning: Attaching a Method to an Object
let fireTruck = { name: "Fire Truck with Remote Control", originalPrice: 15.50, description: 'This toy is mostly made of plastic with an motor inside.', requiresBatteries: true }; let buildingBlock = { price: 55.55, definition: '612 Pieces Building Kit', moreInformation: "The package contains different types and shapes of blocks that can be used to create various types of objects.", requiresBatteries: false, summarize: function () { document.querySelector(".toy2a").innerHTML = "<b>Toy Name:</b> " + buildingBlock.definition; document.querySelector("#toy2b").innerHTML = "<b>Price:</b> " + buildingBlock.price; document.querySelector("#toy2c").innerHTML = "<b>Description:</b> " + buildingBlock.moreInformation; document.querySelector("#toy2d").innerHTML = "<b>Batteries Required:</b> " + buildingBlock.requiresBatteries; } }; buildingBlock.summarize(); document.querySelector(".toy1a").innerHTML = "<b>Toy Name:</b> " + fireTruck.name; document.querySelector("#toy1b").innerHTML = "<b>Price:</b> " + fireTruck.originalPrice; document.querySelector("#toy1c").innerHTML = "<b>Description:</b> " + fireTruck.description; document.querySelector("#toy1d").innerHTML = "<b>Batteries Required:</b> " + fireTruck.requiresBatteries;
@{
ViewBag.Title = "Toys Inventory";
}
<h2>Toys Inventory</h2>
<hr />
<ul style="list-style-type: none">
<li class="toy1a"></li>
<li id="toy1b"></li>
<li id="toy1c"></li>
<li id="toy1d"></li>
</ul>
<hr />
<ul style="list-style-type: none">
<li class="toy2a"></li>
<li id="toy2b"></li>
<li id="toy2c"></li>
<li id="toy2d"></li>
</ul>
<script src="~/Scripts/ToyExamination.js"></script>
A Method that Returns a Value
A method can be made to return a value. To do this, follow the same rules for a function. Here is an example:
let bill = {
basicFee: 35.85,
dvr: 10.65,
sports: 8.95,
subTotal: function () {
return bill.basicFee + bill.dvr + bill.sports;
}
};
Practical Learning: Introducing the Parameters of a Method
let fireTruck = { name: "Fire Truck with Remote Control", originalPrice: 25.50, discountRate: 10, // % description: 'This toy is mostly made of plastic with an motor inside.', requiresBatteries: true, discountAmount: function () { return fireTruck.originalPrice * fireTruck.discountRate / 100; }, salePrice: function () { let disc = fireTruck.discountAmount(); return fireTruck.originalPrice - disc; } }; let buildingBlock = { price: 55.55, definition: '612 Pieces Building Kit', moreInformation: "The package contains different types and shapes of blocks that can be used to create various types of objects.", requiresBatteries: false, summarize: function () { document.querySelector(".toy2a").innerHTML = "<b>Toy Name:</b> " + buildingBlock.definition; document.querySelector("#toy2b").innerHTML = "<b>Price:</b> " + buildingBlock.price; document.querySelector("#toy2c").innerHTML = "<b>Description:</b> " + buildingBlock.moreInformation; document.querySelector("#toy2d").innerHTML = "<b>Batteries Required:</b> " + buildingBlock.requiresBatteries; } }; buildingBlock.summarize(); document.querySelector(".toy1a").innerHTML = "<b>Toy Name:</b> " + fireTruck.name; document.querySelector("#toy1b").innerHTML = "<b>Original Price:</b> " + fireTruck.originalPrice; document.querySelector("#toy1c").innerHTML = "<b>Discount Rate:</b> " + fireTruck.discountRate + "%"; document.querySelector("#toy1d").innerHTML = "<b>Discount Amount:</b> " + fireTruck.discountAmount(); document.querySelector("#toy1e").innerHTML = "<b>Sale Price:</b> " + fireTruck.salePrice(); document.querySelector("#toy1f").innerHTML = "<b>Batteries Required:</b> " + fireTruck.requiresBatteries; document.querySelector("#toy1g").innerHTML = "<b>Description:</b> " + fireTruck.description;
@{
ViewBag.Title = "Toys Inventory";
}
<h2>Toys Inventory</h2>
<hr />
<ul style="list-style-type: none">
<li class="toy1a"></li>
<li id="toy1b"></li>
<li id="toy1c"></li>
<li id="toy1d"></li>
<li id="toy1e"></li>
<li id="toy1f"></li>
<li id="toy1g"></li>
</ul>
<hr />
<ul style="list-style-type: none">
<li class="toy2a"></li>
<li id="toy2b"></li>
<li id="toy2c"></li>
<li id="toy2d"></li>
</ul>
<script src="~/Scripts/ToyExamination.js"></script>
Methods and Parameters
Like a regular function, a method of a class can use one or more parameters. When defining the method, add the name of each parameter in the parentheses of the method, In the body of the method, you can use or ignore the parameter.
When calling a method that uses a parameter, you must pass an argument. If the method uses more than one parameter, pass the arguments in the appropriate order.
Practical Learning: Using Parameters to a Method
let fireTruck = { name: "Fire Truck with Remote Control", originalPrice: 25.50, discountRate: 10, // % description: 'This toy is mostly made of plastic with an motor inside.', requiresBatteries: true, discountAmount: function () { return fireTruck.originalPrice * fireTruck.discountRate / 100; }, salePrice: function () { return fireTruck.originalPrice - fireTruck.discountAmount(); } }; let buildingBlock = { unitPrice: 55.55, definition: '612 Pieces Building Kit', moreInformation: "The package contains different types and shapes of blocks that can be used to create various types of objects.", requiresBatteries: false, discountAmount: function (rate: number) { return buildingBlock.unitPrice * rate / 100; }, markedPrice: function (rate: number) { let discount = buildingBlock.discountAmount(rate) return buildingBlock.unitPrice - discount; }, summarize: function () { document.querySelector(".toy2a").innerHTML = "<b>Toy Name:</b> " + buildingBlock.definition; document.querySelector("#toy2b").innerHTML = "<b>Marked Price:</b> " + buildingBlock.unitPrice.toFixed(2); document.querySelector("#toy2c").innerHTML = "<b>Discount Amount:</b> " + buildingBlock.discountAmount(25).toFixed(2); document.querySelector("#toy2d").innerHTML = "<b>Marked Price:</b> " + buildingBlock.markedPrice(25).toFixed(2); document.querySelector("#toy2e").innerHTML = "<b>Batteries Required:</b> " + buildingBlock.requiresBatteries; document.querySelector("#toy2f").innerHTML = "<b>Description:</b> " + buildingBlock.moreInformation; } }; buildingBlock.summarize(); document.querySelector(".toy1a").innerHTML = "<b>Toy Name:</b> " + fireTruck.name; document.querySelector("#toy1b").innerHTML = "<b>Original Price:</b> " + fireTruck.originalPrice.toFixed(2); document.querySelector("#toy1c").innerHTML = "<b>Discount Rate:</b> " + fireTruck.discountRate + "%"; document.querySelector("#toy1d").innerHTML = "<b>Discount Amount:</b> " + fireTruck.discountAmount().toFixed(2); document.querySelector("#toy1e").innerHTML = "<b>Sale Price:</b> " + fireTruck.salePrice(); document.querySelector("#toy1f").innerHTML = "<b>Batteries Required:</b> " + fireTruck.requiresBatteries; document.querySelector("#toy1g").innerHTML = "<b>Description:</b> " + fireTruck.description;
@{
ViewBag.Title = "Toys Inventory";
}
<h2>Toys Inventory</h2>
<hr />
<ul style="list-style-type: none">
<li class="toy1a"></li>
<li id="toy1b"></li>
<li id="toy1c"></li>
<li id="toy1d"></li>
<li id="toy1e"></li>
<li id="toy1f"></li>
<li id="toy1g"></li>
</ul>
<hr />
<ul style="list-style-type: none">
<li class="toy2a"></li>
<li id="toy2b"></li>
<li id="toy2c"></li>
<li id="toy2d"></li>
<li id="toy2e"></li>
<li id="toy2f"></li>
</ul>
<hr />
<script src="~/Scripts/ToyExamination.js"></script>
this Object
To help an object identify its members within its body, the JavaScript language provides an object named this. Therefore, inside the body of an object, to access a member, type this, a period, and the desired member. Here are examples:
let dinosaurSet = { name: '3-Pack Dinosaur Set', discountRate: 50, // % cost: 44.75, description: "The set contains replicas of three different dinosaurs.", discountAmount: function () { return this.originalPrice * this.discountRate / 100; } }
Earlier, we saw that, to access a member of an object in the body of the object, you could use the name of the object. As a result, to access a member of an object in the body of the object, you can use either the name of the object or the this object.
Practical Learning: Using this Object
let fireTruck = { name: "Fire Truck with Remote Control", originalPrice: 25.50, discountRate: 10, // % description: 'This toy is mostly made of plastic with an motor inside.', requiresBatteries: true, discountAmount: function () { return fireTruck.originalPrice * fireTruck.discountRate / 100; }, salePrice: function () { return fireTruck.originalPrice - fireTruck.discountAmount(); } }; let buildingBlock = { unitPrice: 55.55, definition: '612 Pieces Building Kit', moreInformation: "The package contains different types and shapes of blocks that can be used to create various types of objects.", requiresBatteries: false, discountAmount: function (rate: number) { return buildingBlock.unitPrice * rate / 100; }, markedPrice: function (rate: number) { let discount = buildingBlock.discountAmount(rate) return buildingBlock.unitPrice - discount; }, summarize: function () { document.querySelector(".toy2a").innerHTML = "<b>Toy Name:</b> " + buildingBlock.definition; document.querySelector("#toy2b").innerHTML = "<b>Marked Price:</b> " + buildingBlock.unitPrice.toFixed(2); document.querySelector("#toy2c").innerHTML = "<b>Discount Amount:</b> " + buildingBlock.discountAmount(25).toFixed(2); document.querySelector("#toy2d").innerHTML = "<b>Marked Price:</b> " + buildingBlock.markedPrice(25).toFixed(2); document.querySelector("#toy2e").innerHTML = "<b>Batteries Required:</b> " + buildingBlock.requiresBatteries; document.querySelector("#toy2f").innerHTML = "<b>Description:</b> " + buildingBlock.moreInformation; } }; let dinosaurSet = { name: '3-Pack Dinosaur Set', discountRate: 50, // % cost: 44.75, requiresBatteries: false, dinomyte: "The set contains replicas of three different dinosaurs.", discountAmount: function () { return this.cost * this.discountRate / 100; }, finalPrice: function () { return this.cost - this.discountAmount(); }, present: function () { document.querySelector(".toy3a").innerHTML = "<b>Toy Name:</b> " + this.name; document.querySelector("#toy3b").innerHTML = "<b>Original Price:</b> " + this.cost.toFixed(2); document.querySelector("#toy3c").innerHTML = "<b>Discount Rate:</b> " + this.discountRate.toFixed(2); document.querySelector("#toy3d").innerHTML = "<b>Discount Amount:</b> " + this.discountAmount().toFixed(2); document.querySelector("#toy3e").innerHTML = "<b>Sale Price:</b> " + this.finalPrice().toFixed(2); document.querySelector("#toy3f").innerHTML = "<b>Description:</b> " + this.requiresBatteries; document.querySelector("#toy3g").innerHTML = "<b>Description:</b> " + this.dinomyte; } }; document.querySelector("#toy1a").innerHTML = "<b>Toy Name:</b> " + fireTruck.name; document.querySelector("#toy1b").innerHTML = "<b>Original Price:</b> " + fireTruck.originalPrice.toFixed(2); document.querySelector("#toy1c").innerHTML = "<b>Discount Rate:</b> " + fireTruck.discountRate + "%"; document.querySelector("#toy1d").innerHTML = "<b>Discount Amount:</b> " + fireTruck.discountAmount().toFixed(2); document.querySelector("#toy1e").innerHTML = "<b>Sale Price:</b> " + fireTruck.salePrice(); document.querySelector("#toy1f").innerHTML = "<b>Batteries Required:</b> " + fireTruck.requiresBatteries; document.querySelector("#toy1g").innerHTML = "<b>Description:</b> " + fireTruck.description; buildingBlock.summarize(); dinosaurSet.present();
@{
ViewBag.Title = "Toys Inventory";
}
<h2>Toys Inventory</h2>
<hr />
<ul style="list-style-type: none">
<li class="toy1a"></li>
<li id="toy1b"></li>
<li id="toy1c"></li>
<li id="toy1d"></li>
<li id="toy1e"></li>
<li id="toy1f"></li>
<li id="toy1g"></li>
</ul>
<hr />
<ul style="list-style-type: none">
<li class="toy2a"></li>
<li id="toy2b"></li>
<li id="toy2c"></li>
<li id="toy2d"></li>
<li id="toy2e"></li>
<li id="toy2f"></li>
</ul>
<hr />
<ul style="list-style-type: none">
<li class="toy3a"></li>
<li id="toy3b"></li>
<li id="toy3c"></li>
<li id="toy3d"></li>
<li id="toy3e"></li>
<li id="toy3f"></li>
<li id="toy3g"></li>
</ul>
<script src="~/Scripts/ToyExamination.js"></script>
The Object in this Document
this TypeScript Document
When you are writing your TypeScript code in a document, the document in which you are writing your code practically is an object. To get a referrence to that object, declare a variable and assign the this object to it. Here is an example:
let truck = this;
This means that your variable holds a reference to the object in the current document. In fact, your variable becomes an object.
Attaching a Property to this Object
When you have identified the document of your code as an object, you can add properties to it. To attach a property to that object, anywhere in the (same) document, you can type the name of the object, a period, and the desired name of the property. You can then assign a value to that property. Here is an example:
let truck = this;
truck.name = "Classic Construction Truck";
Remember that the object in the document is referred to as this. Therefore, you can also use the this object to add a new property to the object. Here is an example:
let truck = this;
truck.name = "Classic Construction Truck";
this.itemNumber = 979549;
To access a property of the object, such as to display its value on a webpage, you can use either the name of the object or the this object.
Practical Learning: Attaching a Property to this Object
let truck = this; truck.name = "Classic Construction Truck"; this.itemNumber = 979549; truck.price = 35.95; truck.requiresBatteries = false document.querySelector("#toyName").innerHTML = this.name; document.querySelector("#itemNbr").innerHTML = truck.itemNumber; document.querySelector("#mustUseBatteries").innerHTML = this.requiresBatteries; document.querySelector("#toyPrice").innerHTML = this.price.toFixed(2);
@{ ViewBag.Title = "Toy Presentation"; } <h2>Toy Presentation</h2> <hr /> <p><b>Item #:</b> <span id="itemNbr"></span></p> <p><b>Product Name:</b> <span id="toyName"></span></p> <p><b>Unit Price:</b> <span id="toyPrice"></span></p> <p><b>Unit Price:</b> <span id="mustUseBatteries"></span></p> <script src="~/Scripts/ToyExamination.js"></script>
A Function in this Object
In our introduction to functions, we saw that you can create a function in a TypeScript document. You can then call the function. Here is an example:
View: Presentation.cshtml
@{ ViewBag.Title = "Pronounce"; } <h2>Pronounce</h2> <p id="say"></p> <script src="~/Scripts/Welcome.js"></script>
TypeScript File: Welcome.ts
function sayItLoud() {
document.querySelector("#say").innerHTML = "Welcome to TypeScript.";
}
sayItLoud();
Now that we know that that document in which the code is written is an object and represents the this object. As a result, since the function is created in the object-based document, that function becomes a method (a function member) of the local object. To call the function/method, you can precede it with this.. Here is an example:
function sayItLoud() {
document.querySelector("#say").innerHTML = "Welcome to TypeScript.";
}
this.sayItLoud();
The Methods of this Object
You can attach methods to the object that covers a TypeScript file. As seen for the properties, to attach a method to the object, you can use either the name of the object or the this object, followed by a period and the name of the method. Assign function() {} to it. In the body of the method, you can use the name of the object or the this object to access another member of the same object. Outside the method and in the document, you can use the name of the object or the this object to call the method.
Practical Learning: Attaching a Method to this Object
let truck = this; this.price = 115.72; truck.itemNumber = 394758; this.name = "Junior Education Tablet"; truck.requiresBatteries = false truck.presentation = function () { document.querySelector("#itemNbr").innerHTML = truck.itemNumber; document.querySelector("#toyName").innerHTML = this.name; document.querySelector("#toyPrice").innerHTML = this.price.toFixed(2); document.querySelector("#mustUseBatteries").innerHTML = this.requiresBatteries; }; this.presentation();
An Object as a Property
Introduction
So far, we used numbers and strings as the values of properties. In reality, the value of a property can be anything, including an object.
An Object as the Value of a Property
To make an object the value of a property, specify {} as the value of the property. Here is an example:
let vehicle = {
tagNumber: '972W149',
make: "Ford",
model: 'Taurus',
owner: {}
}
In the body of the child object, you can create the members the same ways we have proceed so far. Here are examples:
let vehicle = {
tagNumber: '972W149',
owner: {
fullName: "Paul Motto",
address: '2937 Fulton Drv',
drvLicNbr: "938-475-960"
}
}
In the same way, you can create as many object-based properties as you want in an object. Here are examples:
let vehicle = { tagNumber: '972W149', owner: { fullName: "Paul Motto", address: '2937 Fulton Drv', drvLicNbr: "938-475-960" }, weight: 3624, definition: { make: "Ford", model: 'Taurus', year: 2016, color: "Dark Green" } }
Accessing a Child Object
To access an object create in another object, use the child's name. To access an internale object outside the parent object, type the name of the parent object, a period, the name of the property that owns the internal object, a period, and the name of the child object. You can then use a property of the child object anywhere you see fit. Here is an example:
View: Administration.cshtml
@{ ViewBag.Title = "Vehicle Registration"; } <h2>Vehicle Registration</h2> <p><b>Tag #:</b> <span id="tagNbr"></span></p> <p><b>Owner:</b> <span id="owner"></span></p> <p><b>Driver's Lic. #:</b> <span id="dln"></span></p> <p><b>Residence:</b> <span id="ha"></span></p> <p><b>Vehicle:</b> <span id="car"></span></p> <p>Weight: <span id="weight"></span> Lbs</p> <script src="~/Scripts/VehiclesDepartment.js"></script>
TypeScript File: VehicleRegistration.ts
let vehicle = { tagNumber: '972W149', owner: { fullName: "Paul Motto", address: '2937 Fulton Drv', drvLicNbr: "938-475-960" }, weight: 3624, definition: { make: "Ford", model: 'Taurus', year: 2016, color: "Dark Green" } }; document.querySelector("#tagNbr").innerHTML = vehicle.tagNumber; document.querySelector("#weight").innerHTML = vehicle.weight.toString(); document.querySelector("#owner").innerHTML = vehicle.owner.fullName; document.querySelector("#dln").innerHTML = vehicle.owner.drvLicNbr; document.querySelector("#ha").innerHTML = vehicle.owner.address; document.querySelector("#car").innerHTML = vehicle.definition.year + ", " + vehicle.definition.make + " " + vehicle.definition.model + " " + vehicle.definition.color;
The Constructors of an Object
Introduction
A constructor is a special function that is used to initialize an object. This means that the function can be used to provide initial values to the properties of the object or to call some functions or methods as soon as the object is accessed.
An Anonymous Constructor
When we reviewed the characteristics of functions, we saw that one way to create a function is to assign function () {} to a variable. Here is an example:
let bill = function () { };
In the body of the function, create the members of the object. Each member must be created using the this object. Here is an example:
let bill = function() { this.basicFee : 45.05; this.dvr : 9.95; this.sports : 12.45; };
Since the properties have been attached to the this object, you can access them using that same this object. Here is an example:
View: BillPreparation.cshtml
@{ ViewBag.Title = "Bill Evaluation"; } <h2>Eastern Shore Cable and Production Entertainment</h2> <fieldset> <legend>Bill Evaluation</legend> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <span id="CableTVBasicFee"></span> </div> <div> <label for="DVRService">DVR Service:</label> <span id="DVRService"></span> </div> <div> <label for="SportPackage">Sport Package:</label> <span id="SportsPackage"></span> </div> </fieldset> <script src="~/Scripts/BillEvaluation.js"></script>
TypeScript File: Preparation.ts
let bill = function() { this.basicFee = 18.86; this.dvr = 4.88; this.sports = 8.58; }; document.querySelector("#CableTVBasicFee").innerHTML = this.basicFee; document.querySelector("#DVRService").innerHTML = this.dvr; document.querySelector("#SportsPackage").innerHTML = this.sports;
The function created above is a constructor. As mentioned previously, it is used to initialize the object. This means that, if you want to access the values of the properties, you must first call the function. Here is an example:
let bill = function() {
this.basicFee = 18.86;
this.dvr = 4.88;
this.sports = 8.58;
};
bill();
document.querySelector("#CableTVBasicFee").innerHTML = this.basicFee;
document.querySelector("#DVRService").innerHTML = this.dvr;
document.querySelector("#SportsPackage").innerHTML = this.sports;
A Named Constructor
In the above example, we first declared a variable and assigned function() {} to it. As an alternative, you can directly provide a name to the constructor. Other than that, you can use and call the constructor as we saw previously. Here is an example:
function bill () { this.basicFee = 18.86; this.dvr = 4.88; this.sports = 8.58; }; bill(); document.querySelector("#CableTVBasicFee").innerHTML = this.basicFee; document.querySelector("#DVRService").innerHTML = this.dvr; document.querySelector("#SportsPackage").innerHTML = this.sports;
Immediately Calling a Constructor
In traditional object-oriented languages (C++, Java, C#, Visual Basic, Object Pascal, etc), the constructor is immediately called when an object is created. To get the functionality in JavaScript, we can include a constructor in () followed by (); Here is an example:
(function bill () {
this.basicFee = 18.86;
this.dvr = 4.88;
this.sports = 8.58;
})();
document.querySelector("#CableTVBasicFee").innerHTML = this.basicFee;
document.querySelector("#DVRService").innerHTML = this.dvr;
document.querySelector("#SportsPackage").innerHTML = this.sports;
A Constructor with Parameters
When creating a function that acts as a constructor, you can add one or more parameters to it. 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. Here is an example:
function bill (cost: number, recording: number, sport: number) {
this.basicFee = cost;
this.dvr = recording;
this.sports = sport;
};
bill(29.17, 8.72, 12.64);
document.querySelector("#CableTVBasicFee").innerHTML = this.basicFee;
document.querySelector("#DVRService").innerHTML = this.dvr;
document.querySelector("#SportsPackage").innerHTML = this.sports;
Functions and Objects
An Object in a Function
In the body of a function, you can create an object. To start, declare a variable using the var or the let keyword and assign {} to it. Here is an example:
function evaluatePayment() {
let basicFee: number = 24.95;
let discountRate: number = 20;
let customer = {
};
}
In the body of the object, create the desired properties using the techniues we have used so far. Here is an example:
function evaluatePayment() {
let basicFee: number = 24.95;
let discountRate: number = 20;
let customer = {
firstName : "Samuel",
lastName : "Clarington",
address : "1806 Bakken Drive",
city : "Rockville",
county : "Montgomery",
state: "MD"
};
let 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:
View: BillPreparation.cshtml
@{ ViewBag.Title = "Bill Evaluation"; } <h2>Eastern Shore Cable and Production Entertainment</h2> <fieldset> <legend>Bill Evaluation</legend> <fieldset> <legend>Customer Information</legend> <div> <label for="accountNumber">Account #:</label> <span id="accountNumber" name="accountNumber" /> </div> <div> <label for="customerName">Full Name:</label> <span id="customerName" name="customerName" /> </div> </fieldset> <hr /> <div> <label for="CableTVBasicFee">Cable TV Basic Fee:</label> <span id="CableTVBasicFee" name="CableTVBasicFee" value="0.00" /> </div> <div> <label for="DVRService">DVR Service:</label> <span id="DVRService" name="DVRService" value="0.00" /> </div> <div> <label for="SportsPackage">Sports Package:</label> <span id="SportsPackage" name="SportsPackage" value="0.00" /> </div> <div> <label for="PaymentAmount">Payment Amount:</label> <span id="PaymentAmount" name="PaymentAmount" value="0.00" /> </div> </fieldset> <script src="~/Scripts/BillEvaluation.js"></script>
TypeScript File: Evaluation.ts
(function evaluatePayment() { let basicFee: number = 24.95; let dvr: number = 9.90; let sport: number = 8.90; let amount: number = basicFee + dvr + sport; let customer = { accountNumber: 284705, firstName: "Samuel", lastName: "Clarington", address: "1806 Bakken Drive", city: "Rockville", county: "Montgomery", state: "MD" }; document.querySelector("#CableTVBasicFee").innerHTML = basicFee.toFixed(2); document.querySelector("#DVRService").innerHTML = dvr.toFixed(2); document.querySelector("#SportsPackage").innerHTML = sport.toFixed(2); document.querySelector("#PaymentAmount").innerHTML = amount.toFixed(2); document.querySelector("#customerName").innerHTML = customer.firstName + ' ' + customer.lastName; document.querySelector("#accountNumber").innerHTML = customer.accountNumber.toFixed(2); })();
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 keyword to produce 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:
View: ToysInventory.cshtml
@{ ViewBag.Title = "Toys Inventory"; } <h2>Toys Inventory</h2> <ul style="list-style-type: none;"> <li><b>Item #:</b> <span id="itemNbr"></span></li> <li><b>Toy Name:</b> <span id="tName"></span></li> <li><b>Unit Price:</b> <span id="price"></span></li> </ul> <script src="~/Scripts/ToysCatalogue.js"></script>
TypeScript File: Catalogue.ts
function create() { let toy = { itemNumber: 937495, toyName: "Mini Point of Sale Station", unitPrice: 32.64 }; return toy; } let mpss = create(); document.querySelector("#tName").innerHTML = mpss.toyName; document.querySelector("#price").innerHTML = mpss.unitPrice.toFixed(2); document.querySelector("#itemNbr").innerHTML = mpss.itemNumber.toString();
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:
function create() {
let toy = {
itemNumber: 937495,
toyName: "Mini Point of Sale Station",
unitPrice: 32.64
};
toy.unitPrice = 27.38;
return toy;
}
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:
function create() {
let identification: string = "Drawing Black Board";
return {
itemNumber: 309581,
toyName: identification,
unitPrice: 18.45
};
}
let mpss = create();
document.querySelector("#tName").innerHTML = mpss.toyName;
document.querySelector("#price").innerHTML = mpss.unitPrice.toFixed(2);
document.querySelector("#itemNbr").innerHTML = mpss.itemNumber.toString();
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:
function create() { return { itemNumber: 749374, toyName: "Kid Ferry Boat", unitPrice: 24.86 }; } function prepare(boat) { document.querySelector("#tName").innerHTML = boat.toyName; document.querySelector("#price").innerHTML = boat.unitPrice.toFixed(2); document.querySelector("#itemNbr").innerHTML = boat.itemNumber.toString(); } var mpss = create(); prepare(mpss);
In the above code, we first defined 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:
function prepare(boat) {
document.querySelector("#tName").innerHTML = boat.toyName;
document.querySelector("#price").innerHTML = boat.unitPrice.toFixed(2);
document.querySelector("#itemNbr").innerHTML = boat.itemNumber.toString();
}
prepare({
itemNumber: 583049,
toyName: "Easter Egg Decorating Set",
unitPrice: 32.04
});
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|