Practical prototype and scipt.aculo.us part 26

Practical prototype and part 26: 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 7 ADVANCED JAVASCRIPT FUNCTIONAL PROGRAMMING AND CLASS-BASED OOP 141 Brevity Brevity is a by-product of cleanliness. Functions can be named more concisely when they don t have to worry about conflict. Which would you rather type stringReplace bar r z bar .replace r z The second option is seven characters shorter than the first. Over time this savings will add up your code will be clearer and your wrists will thank you. Remedial OOP Namespacing Before we get into true OOP let s look at how objects can be used to isolate our code and make it more resilient in a shared scripting environment. Because scripts from different authors often coexist on the same page it s a bad idea to define too many functions in the global scope. The more there are the more likely one of them will overwrite someone else s function with the same name. Instead what if you were to define one object in the global scope and then attach all your functions to that object You d balk at defining a method named run but is much less risky. The first line of defense in the cleanliness wars is namespacing your code. Let s look at some of our code from a previous chapter function submitBreakfastLogEntry event if cancel cancelBreakfastLogEntry event . et cetera function cancelBreakfastLogEntry event form .clear . et cetera Since they re related these functions ought to be placed into a common namespace. 142 CHAPTER 7 ADVANCED JAVASCRIPT FUNCTIONAL PROGRAMMING AND CLASS-BASED OOP var BreakfastLog submitEntry function event form if cancel event et cetera cancelEntry function event . et cetera Here we re using the familiar object literal in a new way as a container for likeminded methods and variables. Remember that is a shortcut for new Object and that the new keyword triggers a new scope. Thus inside any particular method the keyword this refers to the .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
14    358    3    29-04-2024
6    81    2    29-04-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.