1. Trang chủ
  2. » Công Nghệ Thông Tin

Practical prototype and scipt.aculo.us part 4 pptx

6 190 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 6
Dung lượng 87,49 KB

Nội dung

These are the constructors for data types. But instances of these data types also inherit from Object: ['foo', 'bar'] instanceof Object; // (Array literal) //-> true /.*/ instanceof Object; // (RegExp literal) //-> true new Date instanceof Object; //-> true But here’s where it gets tricky. The typical “primitives” in a programming language— strings, numbers, and Booleans—are both primitives and objects in JavaScript. They’re treated as one or the other depending on context. "foo" instanceof Object; //-> false new String instanceof Object; //-> true 5 instanceof Object; //-> false new Number(5) instanceof Object; //-> true true instanceof Object; //-> false new Boolean(true) instanceof Object; //-> true This is confusing at first, but ends up being quite helpful. It allows these types to behave like primitives when they need to (they’re passed by value, instead of by refer- ence), but they can still reap the benefits of JavaScript’s object-oriented functionality (instance methods, local scope, etc.). All Objects Have Prototypes Although JavaScript is most certainly object oriented, it’s likely not the sort of object ori- entation you’re used to. Strictly speaking, there is no concept of a “class” in JavaScript— instead of outlining an abstract definition of an object, you can simply make a copy of an existing object. Remember what we just found out: Array instanceof Object; //-> true new Array instanceof Object; //-> true There is no technical distinction between Array and instances of Array. You can do the same sorts of things to either one. Because there are no classes in JavaScript, inheritance is based on the concept of prototypes. Each object has its own prototype property, which serves as a template for any new instances (copies) made from that object. CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM 5 This behavior isn’t limited to user-defined objects—it can be applied to the built-ins as well. It’s quite simple to add instance methods to arrays, strings, or any other native types: Array.prototype.double = function() { var newArray = []; // inside this function, "this" refers to the array for (var i = 0, length = this.length; i < length; i++) { newArray.push(this[i]); newArray.push(this[i]); } return newArray; }; var exampleArray = new Array(1, 2, 3); // inherits all the properties of Array.prototype exampleArray.double(); //-> [1, 1, 2, 2, 3, 3] Since exampleArray is an instance of Array, it looks to Array.prototype for inheritance. So instead of defining a double function in the global namespace, we can define it as an instance method on arrays. This is a big win. It makes user-written code mesh better with native code, it reduces verbosity and the risk of naming collisions, and it lets the code demonstrate its meaning far more plainly. Those of you more at home with class-based inheritance need not bother with any of this: Prototype includes a more conventional system of OOP that allows for the distinc- tion between classes and instances—and makes dealing with prototypes unnecessary, if that’s your bag. Prototypal inheritance isn’t something you need to be afraid of, but you don’t need to invite it over for a beer, either. Any Object Can Have Arbitrary Properties Set All objects are mutable in JavaScript: they can be changed, augmented, and pruned at any time. You can assign any property to an object, even one that already exists. var object = new Object(); object.foo = "foo"; object.bar = "bar"; for (var i in object) console.log(i); //-> foo //-> bar CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM6 // Numbers have a native "toString" method var number = 5; number.toString(); //-> "5" Number.prototype.toString = function() { return String(this + 1); }; number.toString(); //-> "6" That last example should frighten you—yes, JavaScript’s dynamism lets you do vacu- ously stupid things. Remember that you’re working in a shared environment—don’t do things that will wantonly break other scripts on the page. ABOUT CONSOLE.LOG Many of the code examples in this book will use console.log, a function for writing to the browser console. Supported in Firefox (through the excellent Firebug extension) and Safari, it’s far less invasive than the popular alert function—there are no pop-up dialogs to dismiss. Think of it as JavaScript’s print statement. You won’t ever use it in production code, but it’s handy for learning and debugging. Even Functions Are First-Class Objects JavaScript functions are not the downtrodden plebeians of PHP or Java. They enjoy full citizenship. A function can be assigned to a variable, can be passed as an argument in another function, and can be returned from a function. (You can have a function that accepts a function as an argument and returns a function! Madness!) You’re probably familiar with this syntax for defining functions: function lambda() { return "foo"; } But here’s a lesser-used syntax that’s nearly equivalent: var lambda = function() { return "foo"; }; In both examples, you’re describing a function and assigning it a name of lambda.In both examples , the function can be called by writing lambda(). And in both examples, you can use lambda as flexibly as you’d use any other data type. CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM 7 The second example uses a function literal (or anonymous function): a special, flexible syntax for creating a new function. Just like strings (quotation marks), arrays (brackets), objects (braces), and regular expressions (forward slashes), functions have a literal notation. (Notice also how the second example ends with a semicolon after the closing brace, since the braces aren’t a control structure like they are in the first example.) Prototype uses function literals all over the place. You’ll see them passed as argu- ments into methods for working with collections. You’ll see them used as callbacks for Ajax requests. You’ll see them used to define methods on objects. About the DOM The Document Object Model (DOM), an interaction model defined by an ambitious and far-reaching set of W3C specifications, lays out the ideal set of objects, methods, and properties to change an HTML or XML document programmatically. The segmentation of the DOM into many different “levels” and “modules” means that the browsers you write code for will have wildly varying levels of DOM support. There are four major implementations of JavaScript and the DOM: Mozilla’s Spider- Monkey, Internet Explorer’s JScript, Opera’s linear_b, and Safari’s JavaScriptCore. While each has its strengths and weaknesses, you will discover very quickly that they are not created equal. It’s Hard to Write Multiplatform JavaScript Most developers have the luxury of writing code toward one target: a compiler or canonical interpreter that implements the given language perfectly. Writing JavaScript for modern browsers will make you realize how much this luxury is taken for granted. It can be an excruciating, wailing-and-teeth-grinding experience. Most of these pains will come not from the language itself, but from what other lan- guages would call the standard library—the APIs we have that connect JavaScript to a web environment. One nagging pain, for instance, comes from the different levels of DOM support. Let’s call these “capabilities.” They’re things that some browsers can do, but that others cannot. A sharper, more chronic pain comes from outright incompatibilities between browsers. The most notable is between Internet Explorer and all other browsers. In all modern versions of Internet Explorer (currently versions 6 and 7), DOM support is mini- mal; the gaps are filled in by Internet Explorer’s legacy API, which predates the DOM. The most agonizing pain, akin to a daily kick in the stomach, comes from what I’ll call “quirks.” Quirks are a diplomatic term for bugs: misimplementations of the DOM spec, memory leaks, and other irrational behavior. These are the largest obstacles to CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM8 developer happiness; they’re hard to diagnose and hard to work around. They’ll leave you staring at your monitor past midnight, bleary eyed and out of ideas. JavaScript frameworks exist to smooth out these cracks. Wherever possible, Proto- type provides a unified API that handles all the ugliness under the hood. Prototype won’t solve all your problems, but it can definitely make the process of writing JavaScript far less unpleasant. It’s Hard to Debug Multiplatform JavaScript The tools that server-side developers have come to rely on—loggers, debuggers, and the like—are not readily available on the client side. Among the major browsers, you’ll find that some are far more helpful than others when you need to fix problems in your code. The best developer tool for JavaScript authors is Firebug, an extension for Mozilla Firefox. Firebug is a dream come true: it provides a logger, a debugger, a DOM inspector, a CSS editor, a rendered source tree, and a code profiler. It is the single biggest reason why Firefox is the browser of choice for JavaScript development. Of course, you’ll also need to test in Internet Explorer, Opera, and Safari. But you’ll likely find it easiest to use Firefox while you write your code. When you get it working, you can test in other browsers to find out if you need to make changes. About This Book You won’t need a legend or translation table to read this book. But there are a few things you should know up front so that you can enjoy this book to the fullest. Firefox Is Used for Nearly All Examples The things that make Firefox the best browser for client-side web development also make it the best browser for an interactive teaching process. In this book, we’ll spend a lot of time in Firefox. One major reason is Firebug ( www.getfirebug.com/), the definitive Firefox exten- sion for web developers. You’ll come to love how the Firebug console speeds up trial-and-error development and lets you learn by experimentation. But another rea- son is the stability of SpiderMonkey (Mozilla’s JavaScript engine) and its broad support for the DOM. Of course, this book is also about writing JavaScript in the real world, so we’ll also be testing our examples in other browsers. But we’ll be following the approach outlined ear- lier: develop in Firefox, and then make it work everywhere else. CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM 9 First Theory, Then Practice You’ll notice that the first half of the book is heavy on abstract examples, and the second half is heavy on concrete examples. This division mirrors the division between Prototype and script.aculo.us: the former builds a rich set of APIs, while the latter uses those APIs to address specific UI needs. Even so, there are a few meanderings. Each chapter of Part 1 will highlight specific ways that Prototype can improve the code you write. Each chapter of Part 2 will give you specific ways to apply the examples to your own web application. About Prototype The origins of Prototype are shrouded in mystery—like Stonehenge, the Dead Sea scrolls, and the universe itself. Well, that may be overstating it. Version 1.0 of Prototype was released in March of 2005. An early README file described the framework this way: Prototype is a JavaScript library that aims to ease development of dynamic web applications. Its development is driven heavily by the Ruby on Rails framework, but it can be used in any environment. Though Prototype has evolved considerably over the last three years, this summary is still stunningly applicable. Prototype’s Philosophy The first version of Prototype was very small. It contained some of the convenience methods that Prototype has become famous for, but most of its 335 lines of code were designed to simplify Ajax and form interaction. Since then, its scope has widened, but its philosophy has not wavered. There is neither a manifesto nor a mission statement, but a handful of principles guide the project: The principle of least surprise: Popularized by Yukihiro Matsumoto, the creator of Ruby, it states that a language, framework, or library should always do the “least sur- prising” thing; it should behave the way the user expects it to. Prototype is meant to be intuitive and easy to learn. CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM10 . lambda(). And in both examples, you can use lambda as flexibly as you’d use any other data type. CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM 7 The second example uses. examples, and the second half is heavy on concrete examples. This division mirrors the division between Prototype and script .aculo. us: the former builds a rich set of APIs, while the latter uses those. it should behave the way the user expects it to. Prototype is meant to be intuitive and easy to learn. CHAPTER 1 ■ WHAT YOU SHOULD KNOW ABOUT PROTOTYPE, JAVASCRIPT, AND THE DOM10

Ngày đăng: 03/07/2014, 01:20