Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Practical prototype and scipt.aculo.us part 7: The information in this book is distributed on an "as is" basis, without warranty Although every pre-caution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. | CHAPTER 2 PROTOTYPE BASICS 23 if person.country USA Object.extend data socialSecurityNumber 456-78-9012 stateOfResidence TX standardTaxDeduction true zipCode 78701 Since objects are passed by reference not value the source object is modified in place. Object.extend also solves our typing woes when extending built-ins Object.extend String.prototype strip function . gsub function . times function . toQueryParams function . for var i in String.prototype console.log i - strip gsub times toQueryParams That s one annoyance out of the way. This construct cuts down on redundancy making code both smaller and easier to read. Prototype uses Object.extend all over the place internally extending built-ins mixing in interfaces and merging default options with user-defined options. 24 CHAPTER 2 PROTOTYPE BASICS WHY NOT USE OBJECT.PROTOTYPE.EXTEND If we were steadfastly abiding by JavaScript s object orientation we d define Object.prototype. extend so that we could say the following var data height 5ft 10in hair brown data.extend socialSecurityNumber 456-78-9012 stateOfResidence TX This may appear to make things easier for us but it will make things much harder elsewhere. Because properties defined on the prototypes of objects are enumerated in a for.in loop augmenting Object.prototype would break hashes for var property in data console.log property - height hair socialSecurityNumber stateOfResidence extend There are ways around this but they all involve changing the way we enumerate over objects. And we d be breaking a convention that s relied upon by many other scripts that could conceivably exist in the same environment as Prototype. In the interest of playing well with others nearly all modern JavaScript libraries abide by a gentleman s agreement not to touch Object.prototype. A Coercing Collections into Arrays Oftentimes in JavaScript you ll have to work with a collection that seems like an array but really isn t. The two major culprits are DOM NodeLists returned by .