290 likes | 465 Views
Javascript Not just for the browser. Connor Dunn. About me. Connor Dunn, 2 nd year computer scientist 4 th year at Warwick (Switched from Maths after the 2 nd year) Academic President of CompSoc Interested in web development, most experience using PHP
E N D
JavascriptNot just for the browser. Connor Dunn
About me • Connor Dunn, 2nd year computer scientist • 4th year at Warwick (Switched from Maths after the 2nd year) • Academic President of CompSoc • Interested in web development, most experience using PHP • Recently (last 6 months) became interested in Javascript and Node
Why Javascript? • Simple, easy to learn syntax, similar to Java or C • Available in most web browsers, on most computers • Becoming more available as a server side alternative • In my opinion an expressive language that allows a flexible style of coding
What will this talk cover? • An introduction to the basics of coding in Javascript • A more detailed look at some interesting features of Javascript: • First class functions and closures • Prototype based object orientation • A look at an example of Javascript on the server using some of the features discussed
Javascript basicsVariables varfoo = "String"; bar = 1; foo = 3; • Dynamically typed variables – values have type, variables do not • "var" keyword creates a local variable, without variable is global (more on scope later)
Javascript basicsStructured syntax Javascript supports structured syntax found in imperative programming languages such as C and Java. if (foo == 3) { alert("Foo is 3"); } else { alert("Foo is not 3"); } while (i < 10) { i = i + 1; alert(i); } for (j = 1; j < 4; j++) { alert(j); } switch (k) { case 1: alert("One"); break; case 2: alert("Two"); break }
Javascript basicsExpressions Triple === is strict and also compares type Logical !, ||, && Comparisons ==, != and ===, !== <, <=, >=, > Arithmetic +,-,*,/,% Bitwise |, ^, &, <<, >>, >>>, ~ String + Ternary ? :
Javascript basicsExample var times = 10; varstr = "Hello"; while (times > 0) { if (result === undefined) { result = ""; } result = result + str; times--; } alert(result);
JavascriptfunctionsSimple functions function add(a, b) { return a+b; } alert(add(1,2)); // Output: 3 • Functions in Javascript can be simply defined using the function keyword.
JavascriptfunctionsAnonymous, first class functions add = function (a, b) { return a+b; }; b = add; alert(add(1,2)); // Output: 3 alert(b(1,2)); // Output: 3 • Functions do not need a name, and can be assigned to variables. • Functions can also be passed as arguments and returned by other functions
JavascriptfunctionsScope var a = 10; var b = 20; function foo() { var a = 30; alert(a); // Output: 30 alert(b); // Output: 20 b = 40; } foo(); alert(a) // Output: 10 alert(b) // Output: 40 • Functions have their own scope in Javascript, variables declared in a function only exist within it.
JavascriptfunctionsClosures // Output a message after a delay function delayMsg(delay, message) { function outputMsg() { alert(message); } setTimeout(outputMsg, delay); } delayMsg(1000, "Hello"); • Functions in Javascript can be declared inside other functions, functions inherit variables from their parent
JavascriptobjectsIntro var car = { colour: "Red", beep: function () { alert("Beep"); } } • Objects do not have classes • Objects can be defined as above with an object literal • Properties of objects are just variables, they can be strings, numbers, functions, other objects, etc. • Properties can be accessed using car.colour or car["colour"] • "Methods" (properties which are functions) can be accessed using car.beep() or car["beep"]();
JavascriptobjectsBuilt in objects • Javascript comes with several built in functions: • String • Date • Array • Boolean • Math • RegExp • Function • Number • These objects provide most of Javascripts built in functionality, e.g. Math.random() to generate random numbers
JavascriptobjectsConstructors function Car(colour) { this.colour = colour; this.beep = function () { alert("Beep"); }; } varmyCar = new Car("Blue"); varyourCar = new Car("Red"); • A constructor in Javascript is simply a function invoked using the "new" keyword. • In the constructor function the "this" keyword becomes the object, therefore any properties set on it become part of the object. • Conventional to use a capital letter for constructors, but not required.
JavascriptobjectsPrototypes function Car(colour) { this.colour = colour; this.beep = function () { alert("Beep"); }; } varmyCar = new Car("Blue"); varyourCar = new Car("Red"); Car.prototype.newColour = function (colour) { this.colour = colour; } myCar.newColour("Green"); • Every instance of a constructor function shares the same prototype object • If a property for the object is accessed but does not exist the prototype object will be checked • In the example myCar.newColour does not exist, so Car.prototype.newColour is used • Allows objects to be extended after they are created • Also allows inheritance by setting the prototype object to the parent.
Next up, an example of a server side Javascript application using Node. But first, any questions so far?
What is Node? • Node is a framework that adds asynchronous (more on this next) I/O (Input/Output) to the V8 Javascript engine (the one developed for Google Chrome) • However, it does not run in the browser, it runs standalone scripts on your server. • See www.nodejs.org
What/Why/How is asynchronous I/O? • I/O is very slow. • Asynchronous I/O means not waiting for the result of the operation, but dealing with the result when it becomes available. • This is done in Node using events and callbacks. sys.exec("ls/").addCallback( function (stdout, stderr) { puts(stdout); } );
A simple web framework • As an example node application for this talk we are going to write a simple web framework in node • It will allow loading of modules to display content to the browser • We will then look at how we could write modules using prototyping and closures in Javascript
A simple web framework • example.com/module/method/var1/var2/ • This will call module.method(var1, var2, ...) • The method will be able to send a response to the users browser • Modules will be loaded by adding them to a special object called "loaded" • Lets look at a module
Our first module // Simple module function Simple() { this.hello = function (req, res, arg) { res.simpleSend("Hello World"); } this.talk = function (req, res, arg) { res.simpleSend("Hi, you said: "+arg.join(" ")); } } // Load module loaded.simple = new Simple();
Our framework // Load node http module var http = require('http'); // Loaded modules var loaded = {}; // HTTP Server http.createServer(function (req, res) { // Helper response function res.simpleSend = function (content) { this.sendHeader(200, {'Content-Type': 'text/plain'}); this.sendBody(content); this.finish(); }; // Check the URL if (req.uri.path != '/' && req.uri.path != '') { var module = req.uri.path.split('/'); // Check the module and method exist if (module.length > 2 && loaded[module[1]] !== undefined && (modname = loaded[module[1]]) && modname[module[2]] !== undefined) { modmethod= modname[module[2]]; module.splice(0,3); modmethod(req, res, module); return; } } res.simpleSend("Default response"); }).listen(8000);
Extending our module function Advanced() { this.multiply = function (req, res, arg) { if (arg.length > 1) { res.simpleSend("Result: "+(arg[0] * arg[1])); } else { res.simpleSend("Requires 2 numbers"); } } } // Load simple's methods into advanced Advanced.prototype = new Simple(); // Load advanced loaded.advanced = new Advanced();
Further extensions // Add a method to simple loaded.simple.bye= function (req, res, arg) { res.simpleSend("Goodbye World"); } // Alternative way to add a method (see next slide) Advanced.prototype.add= function (req, res, arg) { if (arg.length > 1) { res.simpleSend("Result: "+(parseInt(arg[0], 10) + parseInt(arg[1], 10))); } else { res.simpleSend("Requires 2 numbers"); } }
Even further extensions // Adds a method to both simple and advanced. Simple.prototype.random= function (req, res, arg) { switch (Math.round(Math.random())) { case 0: res.simpleSend("Hello"); break; case 1: res.simpleSend("Goodbye"); break; } }
Another module using closures function Delay() { this.wait = function (req, res, arg) { if (arg.length > 1) { var delayed = function () { res.simpleSend(arg[1]); }; setTimeout(delayed, arg[0]); } else { res.simpleSend("Requires a number and content"); } }; } loaded.delay = new Delay();
A more advanced delay method Delay.prototype.doin = function (req, res, arg) { if (arg.length > 2) { setTimeout(function () { varmodname = arg[1]; varmodmethod = arg[2]; arg.splice(0, 3); loaded[modname][modmethod](req, res, arg); }, arg[0]); } else { res.simpleSend("Error"); } }
The End • Slides, the full source for the example and instructions on setting up node will be made available on the website • Any questions?