background preloader

Learning JS

Facebook Twitter

Minify JavaScript - Free JavaScript Compressor. Control Flow in Node Part II. Static Version I had so much fun writing the last article on control flow, that I decided to play around with the feedback I received. One thing in particular I want to talk about is the good work inimino is doing. Node has two constructs that are used currently to handle async return values, namely callbacks and event emitters. You can read all about those on the nodejs.org website. I'm going to talk about these and another way to manage asynchronous return values and streaming events.

UPDATE Promises were removed from node a while back, this article has been updated to show callbacks instead of promises. For promises see node-promise. Why the distinction between Callback and EventEmitter? In node there are two event handling techniques. Callback.js var fs = require('fs'); fs.readFile('mydata.txt', function (err, buffer) { if (err) { // Handle error console.error(err.stack); return; } // Do something console.log(buffer);}); http-body.js var http = require('http'); The Node.js Callback style.

Control Flow in Node. Static Version One of the unique aspects of programming in an async framework like node is the ability to decide between which function will run in serial and which will run in parallel. While there are no built-in methods for managing this in node, I'll discuss some of the tricks I came up with while writing the node-blog engine that generates this site. Parallel vs Serial Usually in an application you have steps that can't run until the result from a previous step is known. In normal sequential programming this is easy because every statement waits till the previous one finishes. This is the case in Node too, except for functions that would otherwise perform blocking IO.

For my blog engine I have a tree structure of files that need to be processed. As you can see, there are several items that can be run independent of each other. A counter for grouped parallel actions For the simple case of scanning a directory and reading all the files into one object, we can employ a simple counter. Prototypal Inheritance. Static Version In almost all modern programming languages we use the concept of Object Oriented Programming (OOP) to help manage the complexity of today's software. The biggest challenge in modern software is in fact managing the complexity of it. Most languages do this with a variant OOP called Classical OOP. This is the one you see in Java, C#, C++, PHP, Ruby, and Python. It has the idea that classes should be separate from instances. While this is a great abstraction, I would like to experiment with other ideas.

So what does JavaScript have? From what I hear (I wasn't there at the time), JavaScript was initially a prototypal inheritance system. Classical OOP classical.js var frank = new Person("Frank Dijon");frank.greet(); Output => 'Hello world, my name is Frank Dijon' Here we have a class like object Person. Prototypal OOP I don't like the new keyword, it overloads the meaning of functions and is dangerous. Instead try this on for size: prototypal.js#intro-to-style Using Object.spawn. What is "this"? Static Version Most people that learn JavaScript are coming from a background in another language. This brings with it a view of how the world works that may be different from how it really works in JavaScript.

For this and other reasons, JavaScript is often misunderstood. It's not entirely our fault, the language was designed to work like one thing (scheme-like), but look like another (c-like). This article will describe lexical scope and the "this" variable and how to control them rather than be controlled by them when in coding JavaScript. It's all about where you are. In all programming languages, there is this idea of current scope and current context.

In JavaScript all new scopes are created through "function" definitions. This is an example of global scope: global.js // Define a couple of global variablesvar name = "Tim";var age = 28; // Access one of them from the global scopename; Output => 'Tim' This is an example of local scope: local.js Error ReferenceError: name is not defined => true.

Why use "closure"? Static Version One of the greatest features of the JavaScript language is closure. I've discussed this concept some in the "What is This? " article. There I was explaining scope and context. Today I wish to explain about some practical uses of a closure in event based programming as well as compare it to other methods like object orientation to preserve state across event calls. What is a closure Again from wikipedia: In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Or the way I understand it intuitively: A closure is a function defined within another scope that has access to all the variables within the outer scope. Using closure to hide state Imagine this piece of code: greet_plain.js function greet(message) { console.log(message);} function greeter(name, age) { return name + ", who is " + age + " years old, says hi!

" // Generate the messagevar message = greeter("Bob", 47); // Pass it explicitly to greetgreet(message); Output. Learning Javascript with Object Graphs (Part III) Static Version Part I of this series explained basic object graphs and visually described references, closures, and basic inheritance in JavaScript. Part II compared different styles for doing object-oriented programming in JavaScript. Now in Part III we'll get creative and look as Ruby's object model and compare it to how JavaScript works. Also I'll show how to implement some Ruby style classes. Why Ruby Ok, I'll admit, I used to be a ruby guy. Also I chose ruby because I've noticed that several newcomers to the node.js community come from ruby and other languages with similar object systems.

What are Objects Both languages are object oriented languages. Methods versus Functions Probably the biggest difference between the object models when you get down to it and ignore syntax is the fact that Ruby has methods and JavaScript has first-class functions. Gotta keep them separated In classical OO, there is this idea that you must separate function from state. Controlled Inheritance A String Ruby. Learning Javascript with Object Graphs (Part II) Static Version The first article using graphs to describe JavaScript semantics was so popular that I've decided to try the technique with some more advanced ideas. In this article I'll explain three common techniques for creating objects. They are constructor with prototype, pure prototypal, and object factory. My goal is that this will help people understand the strengths and weaknesses of each technique and understand what's really going on.

Classical JavaScript Constructors First let's create a simple constructor function with a prototype. Classical.js#rectangle function Rectangle(width, height) { this.width = width; this.height = height;}Rectangle.prototype.getArea = function getArea() { return this.width * this.height;};Rectangle.prototype.getPerimeter = function getPerimeter() { return 2 * (this.width + this.height);};Rectangle.prototype.toString = function toString() { return this.constructor.name + " a=" + this.getArea() + " p=" + this.getPerimeter();}; classical.js#square Output. Learning Javascript with Object Graphs. HEADS UP! This article was written for an older version of node. More up-to-date information may be available elsewhere. One of the secrets to being a super effective JavaScript developer is to truly understand the semantics of the language. This article will explain the basic elemental parts of JavaScript using easy to follow diagrams. References Everywhere A variable in JavaScript is simply a label that references a value in memory somewhere.

Local Variables In the following example, we will create four local variables in the top-level scope and point them to some primitive values: variables.js // Let's create some local variables in the top scopevar name = "Tim Caswell";var age = 28;var isProgrammer = true;var likesJavaScript = true;// Test to see if the two variables reference the same valueisProgrammer === likesJavaScript; Notice that the two boolean variables point to the same value in memory. The outer box represents the outermost closure scope. Objects and Prototype Chains objects.js.