background preloader

Prototypal Inheritance

Prototypal Inheritance
Douglas Crockford www.crockford.com Five years ago I wrote Classical Inheritance in JavaScript (Chinese Italian Japanese). It showed that JavaScript is a class-free, prototypal language, and that it has sufficient expressive power to simulate a classical system. My journey was circuitous because JavaScript itself is conflicted about its prototypal nature. new () produces a new object that inherits from .prototype This indirection was intended to make the language seem more familiar to classically trained programmers, but failed to do that, as we can see from the very low opinion Java programmers have of JavaScript. Fortunately, it is easy to create an operator that implements true prototypal inheritance. function object(o) { function F() {} F.prototype = o; return new F(); } The object function untangles JavaScript's constructor pattern, achieving true prototypal inheritance. So instead of creating classes, you make prototype objects, and then use the object function to make new instances.

Prototypal Inheritance Explained Newcomers to JavaScript often misunderstand its object oriented style. Inheritance, in particular, seems foreign to people coming from other object oriented languages like C++ or Java. When I was new to JavaScript, I tried to manipulate the language to fit the style I already knew. But there's a better way. A Different Style C++ and Java are class-based languages. JavaScript is a prototypal language. We start with a function. function Person(name, age) { if (Boolean(name)) this.name = name; if (Boolean(age)) this.age = age; } The function above will be called to initialize new objects. Let's add some functions and properties to be shared among every new Person object. Now let's initialize two new Person objects. var jane = new Person("Jane Smith", 35); var noName = new Person(); noName.setAge(29); The object structure we get looks like this: diagram 1. When we access a property in jane or in noName or in any other new Person object, JavaScript will check in that object first. Success!

Private Members in JavaScript Douglas Crockford www.crockford.com JavaScript is the world's most misunderstood programming language. Some believe that it lacks the property of information hiding because objects cannot have private instance variables and methods. But this is a misunderstanding. JavaScript objects can have private members. Here's how. Objects JavaScript is fundamentally about objects. If a value is a function, we can consider it a method. Objects can be produced by constructors, which are functions which initialize objects. Public The members of an object are all public members. In the constructor This technique is usually used to initialize public instance variables. function Container(param) { this.member = param; } So, if we construct a new object var myContainer = new Container('abc'); then myContainer.member contains 'abc'. In the prototype This technique is usually used to add public methods. Container.prototype.stamp = function (string) { return this.member + string; } So, we can invoke the method Private

Static variables 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. 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 myParenizor = new Parenizor(0); myString = myParenizor.toString(); As you would expect, myString is "(0)". The inherits method is similar to Java's extends. Sugar

Why use the "finally" Block When an exception occurs, execution stops and control is given to the closest exception handler. This often means that lines of code you expect to always be called are not executed. Some resource cleanup, such as closing a file, must always be executed even if an exception is thrown. The Design of Code: Organizing JavaScript Great design is a product of care and attention applied to areas that matter, resulting in a useful, understandable, and hopefully beautiful user interface. But don’t be fooled into thinking that design is left only for designers. There is a lot of design in code, and I don’t mean code that builds the user interface—I mean the design of code. Well-designed code is much easier to maintain, optimize, and extend, making for more efficient developers. There are three high-level, language-agnostic aspects to code design that are particularly important. System architecture—The basic layout of the codebase. In looser languages, specifically JavaScript, it takes a bit of discipline to write well-designed code. One approach I’m fond of consists of a tried-and-true software design pattern, the module pattern, whose extensible structure lends itself to a solid system architecture and a maintainable codebase. The module pattern#section1 Building a module#section2 jQuery plugins#section3 Options#section4

"finally" block JavaScript also allows you to add a "finally" block to the "try-catch" block discussed previously. The "finally" block contains statements that are executed regardless of whether an exception is generated or not in the "try-catch" block. try { execute this block } catch (error) { execute this block if error } finally { execute this block after the try block } If an exception is encountered when running the code within the "try" block, JavaScript will stop execution at that point, and look for a "catch" block to handle it. Take a look at the next example to see how this works: Here's the output: The following error occurred: TypeError - 'a' is undefined Thank you for playing. It's important to note that the code in the "finally" block will be executed even if errors are encountered in the corresponding "try" block.

Introducing Prism: An awesome new syntax highlighter For the past three weeks, on and off, I’ve been working on releasing Dabblet’s syntax highlighter as standalone, since many people had requested it. Zachary Forrest suggested the name “Prism” and I liked it so much I decided to go with it, even though there is an abandoned Mozilla project with the same name. I ended up refactoring and extending it so much that I will need to backport it to Dabblet one of these days! This doesn’t mean I bloated it, the core is still a tiny 1.5KB minified & gzipped. It just means it’s more awesome. In certain ways, Prism is better than any other syntax highlighter I’ve seen: It’s tiny. However, there are some limitations too: Pre-existing HTML in the code block will be stripped off. Enjoy: prismjs.com

Exceprion Handling It's sad but true - error-free code is still largely a Utopian dream. No matter how careful you are, no matter how deep your knowledge or how good your IDE, you're bound to slip up sooner or later. And when you do, and your routines decide to go AWOL, you need to take remedial action. Most programming languages come with built-in exception handling capabilities. These exception handlers make it possible to catch errors and resolve them sensibly, thereby insulating the user from complex decisions and incomprehensible technical information. As a professional developer, you should always wrap your code in exception handling routines, if only to avoid embarrassing flameouts in front of your customers. Up until recently, JavaScript was *not* one of the languages with sophisticated exception handling. That's where this article comes in. The term "exceptions" refers to those errors which can be tracked and controlled. An example might make this clearer. So that's what an error looks like.

Related: