Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript 4 JavaScript 4 Objects and JSON Dr Kevin McManus with material borrowed from Gill Windall

Similar presentations


Presentation on theme: "JavaScript 4 JavaScript 4 Objects and JSON Dr Kevin McManus with material borrowed from Gill Windall"— Presentation transcript:

1 JavaScript 4 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

2 JavaScript 4 © 2015the University of Greenwich 2 Introduction JavaScript is not a truly Object Oriented language unlike Smalltalk, C++ or Java JavaScript is an Object Based language in JavaScript almost everything is an object all primitive types except null and undefined are treated as objects Since XML based web services became pervasive and enabled development of 4 th generation Web 2.0 applications, JavaScript Object Notation (JSON) popularity has increased as an alternative to XML, especially for AJAX approaches to Web application development why? what are the relative merits of JSON and XML?

3 JavaScript 4 © 2015the University of Greenwich 3 Types of JavaScript Objects We have seen that 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 object types the focus of this lecture

4 JavaScript 4 © 2015the University of Greenwich 4 Creating JavaScript Object Types In this example objects are used to represent a single line from an order Each orderLine object has: three properties product unitPrice number two methods calcCost – unit price times number displayLine - to output HTML representing the order line

5 JavaScript 4 © 2015the University of Greenwich 5 General Purpose Object In JavaScript you can instance a general purpose object an associative array of values - properties property value could be a function – method var orderLine1 = new Object(); orderLine1.product = "pencils"; orderLine1.unitPrice = 0.45; orderLine1["number"] = 8; orderLine1.calcCost = calculateLineCost; associative array syntax this function must be previously defined

6 JavaScript 4 © 2015the University of Greenwich 6 General Purpose Object In this example calculateLineCost and displayOrderLine have previously been defined as functions function calculateLineCost() { return this.unitPrice * this.number; } function displayOrderLine() { document.getElementById("invoice").innerHTML += " " + this.product + " " + " " + this.unitPrice + " " + " " + this.number + " " + " " + this.calcCost() + " "; }

7 JavaScript 4 © 2015the University of Greenwich 7 General Purpose Object <!— function calculateLineCost() { return this.unitPrice * this.number; } function displayOrderLine() { document.getElementById("invoice").innerHTML += " " + this.product + " " + " " + this.unitPrice + " " + " " + this.number + " " + " " + this.calcCost() + " "; } generalPurposeObject.html start with the required functions

8 JavaScript 4 © 2015the University of Greenwich 8 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(); orderLine2.writeLine(); } // --> Order Details product price number cost instance an object for pencils instance an object for mugs onload event calls init() data goes in this table

9 JavaScript 4 © 2015the University of Greenwich 9 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?

10 JavaScript 4 © 2015the University of Greenwich 10 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(); objectConstructor.html method name and function name are often the same

11 JavaScript 4 © 2015the University of Greenwich 11 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

12 JavaScript 4 © 2015the University of Greenwich 12 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 = "£"; character reference for £ runs when an OrderLine object is created runs once

13 JavaScript 4 © 2015the University of Greenwich 13 Prototypes Prototype currency : "£" calcCost() { return this.unitPrice * this.number; } writeLine() {... } orderLine1 product : "pencils" price : 0.45 number : 8 orderLine2 product : "mugs" price : 3.00 number : 3

14 JavaScript 4 © 2015the University of Greenwich 14 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

15 JavaScript 4 © 2015the University of Greenwich 15 objectPrototype.html OrderLine Prototype currency : "£" calcCost() { return this.unitPrice * this.number; } writeLine() {... } orderLine1 product : "pencils" unitPrice: 0.45 number : 8 orderLine2 product : "mugs" unitPrice: 3.00 number : 3 currency : "$"

16 JavaScript 4 © 2015the University of Greenwich 16 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 CurrentAccount DepositAccount CashAccountEquityAccount GrowthAccountIncomeAccount

17 JavaScript 4 © 2015the University of Greenwich 17 Inheritance 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 inherits the currency property and calcCost and writeLine methods from OrderLine OrderLineDiscount constructor calcCost method is replaced in the OrderLineDiscount prototype OrderLine OrderLineDiscount

18 JavaScript 4 © 2015the University of Greenwich 18 objectInheritance.html OrderLineDiscount calcCost : calculateLineCostWithDiscount() OrderLine currency : "£" product unitPrice number calcCost() writeLine()

19 JavaScript 4 © 2015the University of Greenwich 19 objectInheritance.html from instance of OrderLineDiscount from instances of OrderLine

20 JavaScript 4 © 2015the University of Greenwich 20 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

21 JavaScript 4 © 2015the University of Greenwich 21 JSON Syntax {"product":"pencils", "unitPrice":0.45, "number":8} fields separated by commas curly braces hold objects field names in quotes name:value pairs numeric values not quoted string values in quotes

22 JavaScript 4 © 2015the University of Greenwich 22 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

23 JavaScript 4 © 2015the University of Greenwich 23 jsonObject.html 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; This is much the same as the generic object example but demonstrates 2 ways of instantiating objects from JSON methods are added after using JSON to create objects with properties JSON notation eval a JSON format string

24 JavaScript 4 © 2015the University of Greenwich 24 Adding Methods JSON can only provide object properties Use JSON in an object constructor to provide methods for the JSON object function OrderLine(obj) { for (var prop in obj) this[prop] = obj[prop]; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } JSON object array syntax

25 JavaScript 4 © 2015the University of Greenwich 25 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); create two JSON objects constructor with methods use the JSON objects to instance two objects with methods

26 JavaScript 4 © 2015the University of Greenwich 26 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

27 JavaScript 4 © 2015the University of Greenwich 27 jsonOrderLine1.php <?php $orderLine = array( 'product' => 'pencils', 'unitPrice' => 0.45, 'number' => 8 ); header('Content-Type: application/json' ); echo json_encode($orderLine); ?> PHP array ends up as a JSON string a more realistic example would obtain the order data from a database

28 JavaScript 4 © 2015the University of Greenwich 28 jsonPrototype.html Asynchronous (AJAX) loading of the JSON service does not guarantee item order

29 JavaScript 4 © 2015the University of Greenwich 29 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"); http.onreadystatechange = handleJsonResponse; //assign callback function

30 JavaScript 4 © 2015the University of Greenwich 30 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); http.send(null); }

31 JavaScript 4 © 2015the University of Greenwich 31 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(); }

32 JavaScript 4 © 2015the University of Greenwich 32 XML to JSON <!ATTLIST price currency ( ukpound | egpound | usdollar | audollar | euro ) "ukpound" > fork 13.69 2 candle 1.99 4 This XML takes a slightly different approach to the data model

33 JavaScript 4 © 2015the University of Greenwich 33 jsonOrdersFromXML.php <?php // load an XML DOM object $url = 'orders.xml'; // this could be a web service $xmlDom = new DOMDocument(); $xmlDom->load($url,LIBXML_NOBLANKS); // convert it into a string - need not have bothered with the DOM $xmlString = $xmlDom->saveXML(); // load the string into a SimpleXML object - strips out the attributes $simpleXML = simplexml_load_string($xmlString); // encode the SimpleXML object as JSON and return it header('Content-Type: application/json'); echo json_encode($simpleXML); ?> JSON but not as we want it

34 JavaScript 4 © 2015the University of Greenwich 34 jsonOrderLinesFromXML.php <?php // read XML data into a DOM object $url = 'orders.xml'; // this could be a web service $xmlDom = new DOMDocument(); $xmlDom->load($url,LIBXML_NOBLANKS); // instantiate an XSLT processor and import XSL file into it $xslt = new XSLTProcessor(); $xslDom = new DOMDocument(); $xslDom->load('orderLines.xsl', LIBXML_NOCDATA); $xslt->importStylesheet($xslDom); // return the transformed XML header('Content-Type: application/json'); echo $xslt->transformToXML($xmlDom); ?> JSON in a more appropriate format

35 JavaScript 4 © 2015the University of Greenwich 35 orderLines.xsl {"orderLine":[ { "product":" ", "unitPrice":, "currency":" ", "number": }, ]} comma delimiter XML attribute becomes a JSON property XML element names translated to JSON property names

36 JavaScript 4 © 2015the University of Greenwich 36 jsonPrototype4.html orderLine from literal JSON orderLines from JSON web service translating XML orderLine from JSON web service this example takes a slightly different approach to handling currency

37 JavaScript 4 © 2015the University of Greenwich 37 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 associative arrays 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 slightly lighter than XML but without readability and validation

38 JavaScript 4 © 2015the University of Greenwich 38 Any Questions?


Download ppt "JavaScript 4 JavaScript 4 Objects and JSON Dr Kevin McManus with material borrowed from Gill Windall"

Similar presentations


Ads by Google