Quests for Knowledge

JavaScript: The Good Parts I

No comments
In JavaScript, the basic types are number, string, boolean, null, and undefined. All other values are objects. The difference between null and undefined is sometimes confusing, but basically, when you set a variable to something, it is not undefined, otherwise it is -- unless, of course, you set the variable to undefined. This isn't something that is particularly new to me, but it was interesting to see the formal definition of the types in plain English. To illustrate, the types variable below is an array of JavaScript's basic types:


The first few chapters of JavaScript: The Good Parts are a basic introduction to JavaScript's types and how they are linked. An especially interesting chapter is Chapter 2: Grammar, where it shows how JavaScript is parsed with railroad diagrams. Here's a railroad diagram for a function literal in JavaScript:


Chapter 3: Objects introduces how JavaScript defines objects. As I've mentioned in a previous post, there are many places where you will find JavaScript looking like a strongly-typed language. There is really no need to treat JavaScript this way as creating an object is as simple as:

Notice that a person object is created directly with Object Literal notation. In this example, person is the prototype used to create the pete object below. The prototype chain could go on forever. Multiple inheritance is achieved by using jQuery's $.extend() method. pete_student is an object that is inherited from student, pete_student_attribs, and pete, which inherits person. Note that the new keyword has not been used in this example.

I can't say that I've had to use JavaScript in this fashion before, but knowing more about how prototypical inheritance works in JavaScript has already proven to be beneficial while debugging or thinking of ways to improve existing code without breaking legacy code.

No comments :

Post a Comment