Advanced JS

Facebook Twitter

Translations/fr_FR at master · rwldrn/idiomatic.js. Javascript : Style et Bonnes pratiques.

JS library

Voyage au coeur de JavaScript (ECMAScript 3) Named function expressions demystified. Introduction Surprisingly, a topic of named function expressions doesn’t seem to be covered well enough on the web.

Named function expressions demystified

This is probably why there are so many misconceptions floating around. In this article, I’ll try to summarize both — theoretical and practical aspects of these wonderful Javascript constructs; the good, bad and ugly parts of them. In a nutshell, named function expressions are useful for one thing only — descriptive function names in debuggers and profilers. Well, there is also a possibility of using function names for recursion, but you will soon see that this is often impractical nowadays. I’ll start with a general explanation of what function expressions are how modern debuggers handle them. Function expressions vs. One of the two most common ways to create a function object in ECMAScript is by means of either Function Expression or Function Declaration. We can see that when identifier is omitted, that “something” can only be an expression.

To demonstrate with examples: Closures. Closures are functions that refer to independent (free) variables.

Closures

In other words, the function defined in the closure 'remembers' the environment in which it was created in. Consider the following: function init() { var name = "Mozilla"; function displayName() { alert (name); } displayName(); }init(); init() creates a local variable name and then a function called displayName(). displayName() is the inner function (a closure) — it is defined inside init(), and only available within the body of that function . Unlike init(), displayName() has no local variables of its own, and instead reuses the variable name declared in the parent function. Run the code and see that this works. Now consider the following example: function makeFunc() { var name = "Mozilla"; function displayName() { alert(name); } return displayName;} var myFunc = makeFunc();myFunc(); That the code still works may seem unintuitive.

The solution to this puzzle is that myFunc has become a closure. Practical closures. Creating your own JavaScript Library. One of the phases I went through while learning about JavaScript was the intense desire to write my own library, similar to jQuery (but massively scaled down).

Creating your own JavaScript Library

My library has gone through several major revisions — and more than one complete re-write, but now is exactly what I started out hoping it would be: functional, clean, small, and a solid learning experience. I’d like to share what I learned from this project, and I hope you share back with me through the comments! Finished project demo Step 1: Identify the purpose of your library This might just be one of the toughest parts of the whole process! Pick one particular function, or aspect of web development/design that you would like your library to handle. I decided my library would be a simple way to manipulate elements visually. Step 2: Mock-up how would use the library You always mock-up a webpage before you start building it right?

Have you ever mocked-up your code? We can also tell some design patterns: Step 3: Code up an outline. Seven JavaScript Things I Wish I Knew Much Earlier In My Career. Advertisement I’ve been writing JavaScript code for much longer than I care to remember.

Seven JavaScript Things I Wish I Knew Much Earlier In My Career

I am very excited about the language’s recent success; it’s good to be a part of that success story. I’ve written dozens of articles, book chapters and one full book on the matter, and yet I keep finding new things. Here are some of the “aha!” Moments I’ve had in the past, which you can try out rather than waiting for them to come to you by chance. Shortcut Notations One of the things I love most about JavaScript now is shortcut notations to generate objects and arrays. Var car = new Object(); car.colour = 'red'; car.wheels = 4; car.hubcaps = 'spinning'; car.age = 4; The same can be achieved with: Much shorter, and you don’t need to repeat the name of the object. The other handy shortcut notation is for arrays. Var moviesThatNeedBetterWriters = new Array( 'Transformers','Transformers2','Avatar','Indiana Jones 4' ); The shorter version of this is: var direction = x < 200 ?

JSON As A Data Format Resources. JavaScript Learning Roadmap. Encapsulation in JavaScript. Download source code - 116 KB Introduction Encapsulation is one of the main concepts in object oriented programming.

Encapsulation in JavaScript

It allows an object to group both private and public members under a single name. All the object oriented programming languages support this. Since JavaScript is also an object oriented programming language, it supports it too. In this article, we will see how to achieve encapsulation in JavaScript by creating a simple object named CssManager that helps to dynamically add, remove, or swap a style-sheet.

Plan Create a namespace named Managers that wraps our object. Code Create a namespace named Managers that will wrap our object In JavaScript, creating a namespace is as simple as creating an object literal. var Managers = {}; Very simple, right? Now you can wrap all the classes and objects related to Managers in a single namespace. Create a singleton object named CssManager Managers.CssManager = { } The code between the pair of curly braces forms the part of the object.

How to use. Extending JavaScript Objects and Classes. Summary You can dynamically create properties and methods of existing objects through simple assignment.Using the prototype property of intrinsic JS Objects, you can extend the functionality of the very objects you know and love in ways that can make your coding far easier.

Extending JavaScript Objects and Classes

Table of Contents Background — Objects in JS In JavaScript, objects can have properties dynamically added to them. [This comes as no surprise to JS programmers who have written something like myObject.backgroundColor='black' or myObject.style.backgroundcolor='black' instead of the correct myObject.style.backgroundColor='black' and consequently pulled out their hair for hours trying to figure out why the background color wasn't changing. For the curious, this feature of JS is possible because the language is evaluated at run-time, and because all Objects are implemented as hash tables. Var spacing = myTable.cellSpacing; var spacing = myTable['cellSpacing']; myTable['% What stupid name!'] The prototype Property. Extending JavaScript Objects and Classes. Summary It is occasionally necessary to create custom unique functions on the fly in JS code at run time.

Extending JavaScript Objects and Classes

This article details the various ways functions may be created on the fly. Ways of defining a function There are two ways to define a function in JS...although enough many people don't know about the versatility of the common method it might be more correct to say there are three ways: The function Keyword This is by far the more common method (and far easier) method of defining a function in JS. Function functionName (parameterList){ statementList } function This required keyword tells JS that you are defining a function. functionName This is the name of the function you wish to define and is, surprisingly to many people, optional. ParameterList An optional list of variable names, separated by commas, which are created as local variables when the function is run and assigned values as passed to the function. statementList function GreetEveryoneAndVIP(vipName){ alert('Hello World! FuncObj. OOP in JS, Part 2 : Inheritance.

In Part 1 we saw how to create classes in JS, including private, privileged, and public properties and methods.

OOP in JS, Part 2 : Inheritance

This section discusses inheritance in Javascript. Summary You cause a class to inherit using ChildClassName.prototype = new ParentClass();. You need to remember to reset the constructor property for the class using ChildClassName.prototype.constructor=ChildClassName. You can call ancestor class methods which your child class has overridden using the Function.call() method. Example To jump right into it, following is a sample showing inheritance between two classes: Using the .constructor property Look at the last line in the above example. Every object instance in JS has a property named constructor that points to its parent class. Mammal.prototype.haveABaby=function(){ var newBaby=new this.constructor("Baby "+this.name); this.offspring.push(newBaby); return newBaby; } ... myPet.haveABaby(); alert(myPet.offspring[0]); Calling 'super' methods The above may look a little bit bizarre.

OOP in JS, Part 1 : Public/Private Variables and Methods. This page shows how to create private variables and methods in "classes" in Javascript through the rather simple example of a person.

OOP in JS, Part 1 : Public/Private Variables and Methods

(This is really a very rough approximation of the classical OOP pattern, and not necessarily a "best-practice" for JavaScript programming.) Part 2 covers inheritance. Summary Example In this example, a person's name and race are set at birth and may never be changed. <- click to run the example code below (the code block being run appears after the Person constructor). The Example Code Notes This page copyright ©2003 by Gavin Kistner. Simple JavaScript Inheritance. I’ve been doing a lot of work, lately, with JavaScript inheritance – namely for my work-in-progress JavaScript book – and in doing so have examined a number of different JavaScript classical-inheritance-simulating techniques.

Simple JavaScript Inheritance

Out of all the ones that I’ve looked at I think my favorites were the implementations employed by base2 and Prototype. I wanted to go about extracting the soul of these techniques into a simple, re-usable, form that could be easily understood and didn’t have any dependencies. Additionally I wanted the result to be simple and highly usable. Here’s an example of what you can do with it: A couple things to note about this implementation: Creating a constructor had to be simple (in this case simply providing an init method does the trick).In order to create a new ‘class’ you must extend (sub-class) an existing class.All of the ‘classes’ inherit from a single ancestor: Class.

Simple Class Creation and Inheritance Initialization if ( ! Super Method. Classical Inheritance in JavaScript. Douglas Crockford www.crockford.com And you think you're so clever and classless and free — John Lennon JavaScript is a class-free, object-oriented language, and as such, it uses prototypal inheritance instead of classical inheritance. This can be puzzling to programmers trained in conventional object-oriented languages like C++ and Java. JavaScript's prototypal inheritance has more expressive power than classical inheritance, as we will see presently.

But first, why do we care about inheritance at all? The second reason is code reuse. To demonstrate this, we will introduce a little sugar which will let us write in a style that resembles a conventional classical language. Classical Inheritance First, we will make a Parenizor class that will have set and get methods for its value, and a toString method that will wrap the value in parens.

The syntax is a little unusual, but it is easy to recognize the classical pattern in it. So now we can write As you would expect, myString is "(0)". Sugar. Learning JavaScript – Lesson 3: Basic Object Types.