Ceci est une ancienne révision du document !
1
In the first part, I talked about how JavaScript has evolved over the years, what is the current status of the language, and why it is so widely adopted by developers. In this part, I will focus on JavaScript Objects and functions. Since I received an email from Ray (one of our readers, thank you for contacting me) with some questions, I will address these at the end of the article in the Questions and Solutions section. JavaScript Objects In JavaScript, everything is an object, even functions are objects, which, if you are familiar with other programming languages, may seem a little odd. But, don’t worry, this gives JavaScript some real power. JavaScript is a dynamic programming language, which means objects can have different values assigned during runtime, without any problem. For example: var myName = “Greg”; myName = 123; In the first case, the myName stores a string value; in the second case it should store an integer, 123, but JavaScript has a special type, Number (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) to hold numerical values.
Dans la première partie, je vous ai montré comment JavaScript a évolué au fil des ans, l'état actuel du langage, et pourquoi il est si largement adopté par les développeurs. Dans cette partie, je vais me concentrer sur les Objets et les fonctions JavaScript. J'ai reçu un courriel de Ray (un de nos lecteurs, merci de m'avoir contacté) avec quelques questions, j'aborderai celles-ci à la fin de l'article dans la section Questions et Solutions.
Les Objets JavaScript
En JavaScript, tout est un objet, même les fonctions sont des objets, ce qui, si vous êtes familier avec d'autres langages de programmation, peut sembler un peu étrange. Mais, ne vous inquiétez pas, cela donne un réel pouvoir à JavaScript.
JavaScript est un langage de programmation dynamique, ce qui signifie que les objets peuvent avoir différentes valeurs attribuées lors de l'exécution, sans aucun problème. Par exemple :
var monNom = “Greg”; monNom = 123;
Dans le premier cas, la variable monNom stocke une chaîne de caractères ; dans le second cas, elle stocke un nombre entier, 123, mais JavaScript a un type spécial, Number (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) pour contenir des valeurs numériques.
2
Since JavaScript is a dynamic language, I can extend objects in any way I want. For example, if I create a new object: var myHouse = { nrOfRooms:3, size:100 }; It creates an object: Object {nrOfRooms: 3, size: 100} Let’s extend this with a couple of properties: myHouse.price = 1500; myHouse[“currency”] = “USD”; These result is the following object: Object {nrOfRooms: 3, size: 100, price: 1500, currency: “USD”}
3
As you can see, there are three ways to create custom objects: • The first, also called JSON (JavaScript Object Notation), defines objects using the curly braces and specifies the properties and their values separated by a colon. • The second option is to use the . (dot) operator, and write the name of the new property and assign a value to it. • The third option is to use the index [] operator, which receives a string as a parameter and a value to assign. If you know other programming languages, you can imagine JavaScript objects as a kind of special dictionaries or maps. Functions may or may not have return values. In the case of the isBiggerThan() function, I have not specified a return type, nor that it will have a return value, but I could easily return a boolean value (true or false), JavaScript permits this. As an exercise, you can create other objects which simulate real life objects, like a forest which has a function called plantTrees, and receives a parameter nrOfTrees, and it sums up the number of trees in the forest. Or it may store the different types of animals which live in the forest; the topic does not really matter, the idea is to get you familiarized with object notation and function creation, we will use this a lot.
4
Questions and Solutions Question: Ray asked how we can select some information from a file, especially a SQLite database using JavaScript. Solution: There are two approaches, two scenarios. The first one is when you have the SQLite database available on the client machine, where the browser is running. In this case you can use the SQL.js (https://github.com/kripken/sql.js/) library to load the SQLite files. Even more, you can do queries and create data schemas using JavaScript. The page on GitHub has good code examples; you can start using those for loading your database and querying data. The second scenario is when the SQLite database is available only on the web server and the client is accessing the web server through the Internet. In this case, you need to have a server-side component (this can be node.js based) which reads the SQLite database, and, using HTTP requests, sends the data back to the client’s browser. In this case, the client side JavaScript is more complex, because it needs to use AJAX calls to load the data. Here is a sample node.js code which connects to a SQLite database, creates a new table if it does not exist, and inserts two new entries in the table. After the insert it queries the table and writes the data to the console.
5
To execute the code on the previous page, you will need to have node.js (https://nodejs.org/) and npm installed, and install sqlite3 through npm using this command: npm install sqlite3 –save When all is set up, you can run the program using: node sqlite_reader.js Supposing you named your file sqlite_reader.js. The output should look something like that shown above in the command line (I was executing under Windows, but the output is the same under Linux too, since node.js runs the same way in both environments). In future articles, I will present how to create a new HTTP server using node, and how to transfer data from the server side to the client side – everything using JavaScript. I would be happy to hear from you; what are the topics in JavaScript which you would be interested in. Please feel free and email me your topic ideas, the same way as Ray did. Thanks again, Ray!