360 likes | 562 Vues
JavaScript 4 Objects and JSON. Dr Kevin McManus with material borrowed from Gill Windall http://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/JavaScript4.html. Types of Objects. We have seen the JavaScript objects can be classified into three types object types built into the core language
E N D
JavaScript 4Objects and JSON Dr Kevin McManus with material borrowed from Gill Windall http://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/JavaScript4.html
Types of Objects • We have seen the JavaScript objects can be classified into three types • object types built into the core language • e.g. Object, Array, String, Date, Math, RegExp • client-side (or server-side) objects for interacting with the browser and document (or server-side environment) • e.g. document, history, window, navigator • programmer defined types of objects the University of Greenwich
Creating your own object types • In this example objects are used to represent order lines • Each orderLine object has: • three properties • product • unit price • number • two methods • calcCost (price times number) • displayLine (output HTML representing the order line) the University of Greenwich
General Purpose Object • In JavaScript you can simply instance a general purpose object • simply assign properties and methods to it var orderLine1 = new Object(); orderLine1.product = "pencils"; orderLine1.unitPrice = 0.45; orderLine1.number = 8; orderLine1.calcCost = calculateLineCost; orderLine1.writeLine = displayOrderLine; the University of Greenwich
General Purpose Object • calcLineCost and displayOrderLine have previously been defined as functions function calcLineCost(){ returnthis.unitPrice * this.number; } function displayOrderLine(orderTable) { document.getElementById(orderTable).innerHTML += "<tr><td>" + this.product + "</td>" + "<td>" + this.unitPrice + "</td>" + "<td>" + this.number + "</td>" + "<td>" + this.calcCost() + "</td></tr>"; } • The object's properties and methods can be accessed alert(orderLine1.product); orderLine1.writeLine("customer"); the University of Greenwich
generalPurposeObject.html <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" > <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb"> <head> <title>General Purpose Object</title> <script type="text/javascript"> <!-- function calculateLineCost() { returnthis.unitPrice * this.number; } function displayOrderLine(orderTable) { document.getElementById(orderTable).innerHTML += "<tr><td>" + this.product + "</td>" + "<td>" + this.unitPrice + "</td>" + "<td>" + this.number + "</td>" + "<td>" + this.calcCost() + "</td></tr>"; } start with the functions required the University of Greenwich
var orderLine1 = new Object(); orderLine1.product = "pencils"; orderLine1.unitPrice = 0.45; orderLine1.number = 8; orderLine1.calcCost = calculateLineCost; orderLine1.writeLine = displayOrderLine; var orderLine2 = new Object(); orderLine2.product = "mugs"; orderLine2.unitPrice = 3.00; orderLine2.number = 3; orderLine2.calcCost = calculateLineCost; orderLine2.writeLine = displayOrderLine; function init() { orderLine1.writeLine("customer"); orderLine2.writeLine("customer"); } // --> </script> </head><body onload="init()"> <h1>Order Details</h1> <table id="customer"> <tr><th>product</th><th>price</th><th>number</th><th>cost</th></tr></table> instance an object for pencils instance an object for mugs onload event calls init() data goes in this table the University of Greenwich
Questions 1. What do you think would happen if this line orderLine2.unitPrice = 3.00; were mistyped as: orderLine2.unitprice = 3.00; 2. Do you think that JavaScript supports method overloading? the University of Greenwich
Creating Custom Object Types • An object type can easily be created by defining a constructor method function OrderLine(prod, price, numb) { this.product = prod; this.unitPrice = price; this.number = numb; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } var orderLine1 = new OrderLine("pencils",0.45,8); orderLine1.writeLine("customer"); objectConstructor.html method name and function name are often the same the University of Greenwich
Prototypes • In the previous two examples each instance of the object has its own copy of the properties and methods • but the code for the calcCost and writeLine methods are the same for each instance of the type • it is inefficient to store the code in each instance. • The solution is to make use of the object's prototype • every JavaScript object has a prototype the University of Greenwich
Prototypes • If you want all instances of an object type to share a property value or method then you assign it to the constructor's prototype function OrderLine(prod, price, numb) { this.product = prod; this.unitPrice = price; this.number = numb; } OrderLine.prototype.calcCost = calculateLineCost; OrderLine.prototype.writeLine = displayOrderLine; OrderLine.prototype.currency = "£"; runs when an OrderLine object is created runs once character reference for £ the University of Greenwich
Prototypes orderLine1 product : "pencils" price : 0.45 number : 8 orderLine2 product : "mugs" price : 3.00 number : 3 the University of Greenwich
Prototypes • When assigning a property for an object JavaScript doesn't check to see if it exists in the prototype • if necessary the property will be created in the object var orderLine1 = new OrderLine("pencils",0.45,8); var orderLine2 = new OrderLine("mugs",3.00,3); orderLine2.currency = "$"; • a currency property will be created in orderLine2 • overrules the currency of the prototype the University of Greenwich
objectPrototype.html orderLine1 product : "pencils" unitPrice: 0.45 number : 8 orderLine2 product : "mugs" unitPrice: 3.00 number : 3 currency : "$" the University of Greenwich
Inheritance • Most OO languages have a mechanism where you can build hierarchies of object classes • each class inherits properties and methods from it’s parent Account DepositAccount CurrentAccount CashAccount EquityAccount GrowthAccount IncomeAccount the University of Greenwich
Inheritance OrderLine OrderLineDiscount function OrderLineDiscount(prod, price, numb, disc) { this.product = prod; this.unitPrice = price; this.number = numb; this.discount = disc; } OrderLineDiscount.prototype = new OrderLine("", 0, 0); OrderLineDiscount.prototype.calcCost = calculateLineCostWithDiscount; OrderLineDiscount constructor OrderLineDiscount inherits the currency property and calcCost and writeLine methods from OrderLine calcCost method is replaced in the OrderLineDiscount prototype the University of Greenwich
objectInheritance.html from instances of OrderLine from instance of OrderLineDiscount the University of Greenwich
JSON • JavaScript Object Notation • not just for use with JavaScript • Text-based and human-readable • Used to communicate data in the form of serialized objects • an alternative to XML • smaller and quicker to process the University of Greenwich
JSON Syntax curly braces hold objects fields separated by commas {"product":"pencils", "unitPrice":0.45, "number":8} field names in quotes string values in quotes, name:value pairs numeric values not quoted the University of Greenwich
JSON Syntax { "firstName": "Betty", "lastName": "Rubble", "age": 28, "address": { "line1": "21 Main Street", "line2": "Bridport", "county": "Suffolk", "postCode": "BD23 3DG" }, "phoneNumber": [ { "type": "home", "number": "0213454676" }, { "type": "mobile", "number": "07774435674" } ] } objects array of two objects the University of Greenwich
jsonObject.html This is much the same as the generic object example but demonstrates 2 ways of instantiating objects from JSON var orderLine1 = { "product":"pencils", "unitPrice":0.45, "number":8 }; orderLine1.calcCost = calculateLineCost; orderLine1.writeLine = displayOrderLine; var orderLine2txt = '{"product":"mugs","unitPrice":3.00,"number":3}'; var orderLine2 = eval ("(" + orderLine2txt + ")"); orderLine2.calcCost = calculateLineCost; orderLine2.writeLine = displayOrderLine; JSON notation eval a JSON format string methods are added after using JSON to create objects with properties the University of Greenwich
Adding Methods • JSON can only provide object properties • Use JSON in an object constructor to provide methods for the JSON object JSON object array syntax function OrderLine(obj) { for (var prop in obj) this[prop] = obj[prop]; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } the University of Greenwich
jsonConstructor.html function OrderLine(obj) { for (var prop in obj) this[prop] = obj[prop]; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } var jsonOrderLine1 = { "product":"pencils", "unitPrice":0.45, "number":8 }; var orderLine1 = new OrderLine(jsonOrderLine1); var jsonOrderLine2 = { "product":"mugs", "unitPrice":3.00, "number":3 }; var orderLine2 = new OrderLine(jsonOrderLine2); constructor with methods create two JSON objects use the JSON objects to instance two objects with methods the University of Greenwich
JSON Services • In the examples so far JSON has not been much use • the main points about using JSON have been covered • JSON is useful as a serialisation mechanism to transport objects • web services the University of Greenwich
jsonOrderLine1.php PHP array ends up as a JSON string <?php $orderLine = array( 'product' => 'pencils', 'unitPrice' => 0.45, 'number' => 8 ); header('Content-Type: application/json'); echo json_encode($orderLine); ?> A more realistic example would obtain the order data from a database the University of Greenwich
jsonPrototype.html Asynchronous (AJAX) loading of the JSON service does not guarantee item order the University of Greenwich
jsonPrototype.html // OrderLine object constructor function OrderLine(obj) { for (var prop in obj) this[prop] = obj[prop]; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } OrderLine.prototype.currency = "£"; OrderLine.prototype.calcCost = calculateLineCost; OrderLine.prototype.writeLine = displayOrderLine; // instance an XML HTTP request object var http = new XMLHttpRequest(); //no support for IE6 http.overrideMimeType("application/json"); the University of Greenwich
jsonPrototype.html // Event handler for the JSON response function handleJsonResponse() { if (http.readyState == 4) { var jsonOrderLine1 = eval ("(" + http.responseText + ")"); var orderLine1 = new OrderLine(jsonOrderLine1); orderLine1.writeLine("customerTable"); } } // Send request asynchronusly function requestJSON(serviceURL) { http.open("GET",serviceURL,true); //assign callback function http.onreadystatechange = handleJsonResponse; http.send(null); } the University of Greenwich
jsonPrototype.html // instantiate order line 2 object var jsonOrderLine2 = { "product":"mugs", "unitPrice":3.00, "number":3 }; var orderLine2 = new OrderLine(jsonOrderLine2); orderLine2.currency = "$"; // write the objects into the page function init() { // asynchronously request and write order line 1 requestJSON("jsonOrderLine1.php"); // write order line 2 orderLine2.writeLine("customer"); } the University of Greenwich
Summary • JavaScript is object based not object oriented • a scripting language • loosely typed • JavaScript provides object types and permits a number of approaches for user created objects • some are little more than data structures • some demonstrate class-like behaviour with inheritance • JavaScript prototypes lie at the heart of the language • available to users • JSON provides serialisation of JavaScript object properties • required if data is to be transported • slightly more advanced than name value pairs • but not in the examples shown here • slightly simpler than XML • but without validation the University of Greenwich
Any Questions? the University of Greenwich