The Constructors of an Object

Introduction

As constructor is a method that is used to create an object. The objects of JavaScript also support constructors in various ways.

Practical LearningPractical Learning: Introducing Functions

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the New Project dialog box, click ASP.NET Web Application (.NET Framework)
  4. Change project Name to CableCompany1
  5. Click OK
  6. In the New ASP.NET Web Application dialog box, click the MVC icon
  7. Click OK
  8. To create a new CSS file, in the Solution Explorer, right-click CableCompany1 -> Add -> New Item...
  9. In the left frame of the Add New Item dialog box, click Web and click Markup under it. In the middle frame, click Style Sheet
  10. Change the file Name to CableCompany
  11. Click Add
  12. Change the document as follows:
    body {
        background-color: white;
    }
    
    .bold                       { font-weight:      600;}
    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  }
    .containment h1             { margin:           auto;
                                  width:            600px;     }
    .containment form           { margin:           auto;
                                  width:            280px;     }
    .common-font                { font-family:      Garamond, Georgia, 'Times New Roman', serif; }
  13. In the Solution Explorer, under Controllers, doublet-click HomeController.cs
  14. Add a method as follows:
    using System.Web.Mvc;
    
    namespace CableCompany1.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 BillPreparation()
            {
                return View();
            }
        }
    }
  15. Right-click below BillPreparation() and click Add View...
  16. In the Add View dialog box, make sure the View Name text box is displaying BillPreparation. Click Add
  17. Change the document as follows:
    @{
        ViewBag.Title = "BillPreparation";
    }
    
    <div class="containment common-font">
        <h1 class="text-center bold">ESCAPE</h1>
        <h2 class="text-center bold">Eastern Shore Cable and Production Entertainment</h2>
        <h3 class="text-center bold">Bill Evaluation</h3>
    </div>
    
    <div class="containment common-font">
        <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>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script>
        $(document).ready(function () {
            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;
            };
    
            $("#CableTVBasicFee").val(this.basicFee);
            $("#DVRService").val(this.dvr);
            $("#SportsPackage").val(this.sports);
            $("#subTotal").val(this.subTotal());
            $("#countyTaxes").val(this.localTaxes(0.15));
        });
    </script>
  18. To execute the application, press Ctrl + F5:

    Using this Object in Scope

  19. Close the browser and return to your programming environment

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. 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;
};

You can then 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:

@{
    ViewBag.Title = "Bill Evaluation";
}

<div class="containment common-font">
    <h1 class="text-center bold">ESCAPE</h1>
    <h2 class="text-center bold">Eastern Shore Cable and Production Entertainment</h2>
    <h3 class="text-center bold">Bill Evaluation</h3>
</div>

<div class="containment common-font">
    <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>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    'use strict';

    var bill = function () {
        bill.basicFee = 45.05;
        bill.dvr = 9.95;
        bill.sports = 12.45;
    };

    bill();

    $(document).ready(function () {
        $("#CableTVBasicFee").val(bill.basicFee);
        $("#DVRService").val(bill.dvr);
        $("#SportsPackage").val(bill.sports);
    });
</script>

This would produce:

An Anonymous Constructor

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 LearningPractical Learning: Creating a Constructor

  1. Change the document as follows:
    @{
        ViewBag.Title = "BillPreparation";
    }
    
    <div class="containment common-font">
        <h1 class="text-center bold">ESCAPE</h1>
        <h2 class="text-center bold">Eastern Shore Cable and Production Entertainment</h2>
        <h3 class="text-center bold">Bill Evaluation</h3>
    </div>
    
    <div class="containment common-font">
        <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>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script>
        $(document).ready(function () {
            'use strict';
    
            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);
    
            $("#CableTVBasicFee").val(pay.basicFee);
            $("#DVRService").val(pay.dvr);
            $("#SportsPackage").val(pay.sports);
            $("#subTotal").val(pay.subTotal());
            $("#countyTaxes").val(local);
            $("input[name='stateTaxes']").val(state);
            $("input[name='paymentAmount']").val(total + local + state);
        });
    </script>
  2. To execute the project, press Ctrl + F5

    Aligning the Content of a Text Box

  3. Close the browser and return to your programming environment

A Constructor with Parameters

When creating a function that acts as a constructor, you can give 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.

Practical Learning: Passing Arguments to a Constructor

  1. Change the document as follows:
    @{
        ViewBag.Title = "BillPreparation";
    }
    
    <div class="containment common-font">
        <h1 class="text-center bold">ESCAPE</h1>
        <h2 class="text-center bold">Eastern Shore Cable and Production Entertainment</h2>
        <h3 class="text-center bold">Bill Evaluation</h3>
    </div>
    
    <div class="containment common-font">
        <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="fccFee">FCC Fee:</label>
                    <input type="number" id="fccFee" class="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>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script>
        $(document).ready(function () {
            'use strict';
    
            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;
            };
    
            var pay = create(28.85, 8.88, 7.95);
    
            var pay = create(28.85, 8.88, 7.95);
    
            var st = pay.subTotal();
            var local = pay.calcTaxes(0.15);
            var state = pay.calcTaxes(0.05);
    
            $("#CableTVBasicFee").val(pay.basicFee);
            $("#DVRService").val(pay.dvr);
            $("#SportsPackage").val(pay.sports);
            $(".fccFee").val(pay.fccFee);
            $("#subTotal").val(st);
            $("#countyTaxes").val(local);
            $("input[name='stateTaxes']").val(state);
            $("input[name='paymentAmount']").val(st + local + state);
        });
    </script>
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    Passing Arguments to a Constructor

  3. Close the form and return to your programming environment

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.

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.

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.

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();

    . . .

    function create() {
        var toy = {
            itemNumber: 937495,
            toyName: "Mini Point of Sale Station",
            unitPrice: 32.64
        };

        toy.unitPrice = 27.38;

        return toy;
    }
</script>

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();

    . . .

    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) {
        . . . = play.itemNumber;
        . . . = play.toyName;
        . . . = 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) {
        . . . = play.itemNumber;
        . . . = play.toyName;
        . . . = play.unitPrice;
    }

    prepare({
        itemNumber: 583049,
        toyName: "Easter Egg Decorating Set",
        unitPrice: 32.04
    });
</script>
</body>
</html>

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2017-2019, FunctionX Next