Practical prototype and scipt.aculo.us part 32

Practical prototype and part 32: 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. | 178 CHAPTER 8 OTHER HELPFUL THINGS USEFUL METHODS ON BUILT-INS Advanced Replacement Recall in the previous chapter how we created classes for football players where each instance of a class was a specific player. Each had properties like firstName lastName and points that held useful metadata about the player. We also defined a custom toString method taking advantage of the fact that JavaScript uses a method by that name whenever it needs to coerce an object into a string. Our toString method returned the first and last names of the player var qb new Quarterback Andrew Dupont qb - Object qb just won the Heisman trophy. - Andrew Dupont just won the Heisman trophy. Because concatenating a string to another object involves automatic string coercion our instance of Quarterback knew how to represent itself in that context. Template and String interpolate do something similar. If the object you re interpolating with has a special method called toTemplateReplacements then the result of that method will be used to fill in the template string var blatantLie new Template position firstName lastName just won the Heisman trophy. qb - Andrew Dupont just won the Heisman trophy. adding an instance method to the Quarterback class Quarterback toTemplateReplacements function return position QB firstName lastName qb - QB Andrew Dupont just won the Heisman trophy. Here we ve done a before-and-after comparison. The first time we call Template evaluate the Quarterback instance itself is used its own properties filling CHAPTER 8 OTHER HELPFUL THINGS USEFUL METHODS ON BUILT-INS 179 in the holes of the template string. That instance has firstName and lastName properties but it doesn t have a position property so an empty string is used instead. When we add Quarterback toTemplateReplacements though we re supplying a substitute object to use for interpolation. So we re able to specify properties above and .

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
187    27    1    30-11-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.