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!
Public, Privileged, Private
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
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.
"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.
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.
You must remember 'this'
Of all the tech blogs in all the sites in all the worldwide web, you walk into mine... If you hang out in JavaScript-oriented newsgroups like these for any length of time, you will eventually see some variation of this question: Hey, why doesn't this work?function MyWidget(name){ this.name = name; this.element = null;}MyWidget.prototype.showName = function(){ alert('The name is ' + this.name);}MyWidget.prototype.hookElement = function(element){ this.element = element; Event.observe(this.element, 'click', this.showName);}function test(){ var widget; widget = new MyWidget('Test Name'); widget.hookElement(document.getElementById('testDiv'));}"testDiv" is a div in the document, and I know that I'm not calling the test() function before the DOM is loaded, so why is it when I click the div I get the message "The name is undefined"?! (As always, I'm using some convenience syntax in the above for hooking up the event handler.) The OP (original poster) might even follow on with: And that's it!
Object-Oriented JavaScript
Over recent years, JavaScript has increasingly gained popularity, partly due to libraries that are developed to make JavaScript apps/effects easier to create for those who may not have fully grasped the core language yet. While in the past it was a common argument that JavaScript was a basic language and was very 'slap dash' with no real foundation; this is no longer the case, especially with the introduction of high scale web applications and 'adaptations' such as JSON (JavaScript Object Notation). JavaScript can have all that an Object-Orientated language has to offer, albeit with some extra effort outside of the scope of this article. Congratulations, you just created an object. For each of the objects we have created a property 'iAm' which contains a string value that is used in our objects method 'whatAmI' which alerts a message. Properties are variables created inside an object and methods are functions created inside an object. First we will create an Object literal;
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. 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 Super Method