Practical prototype and scipt.aculo.us part 29

Practical prototype and part 29: 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 159 Functions Can Have Their Own Methods Imagine I ve got a function that adds numbers together function sum var num 0 for var i 0 i i num arguments i return num The sum function will add its arguments together and return a number. If no arguments are given it will return 0. We know the syntax for calling this method var result sum To call this function we append empty parentheses. If we take the parentheses off though we re no longer calling the function we re just referring to it var result sum Be sure you understand the difference. In the first example result is set to 0 the result of calling sum with no arguments. In the second example result is set to the sum function itself. In effect we re giving sum an alias. var result sum result 2 3 4 - 9 We re going to look at a few instance methods of Function. At first these may seem like magic tricks but they ll become more intuitive the more you use them. Using Function curry Partial application or currying is a useful technique in languages where functions are first-class objects. It s the process by which you preload a number of arguments into a function. In other words I could curry a function that expects parameters a b and c by giving it a and b ahead of time getting back a function that expects only c. Confused yet What I just said is much easier to express in code 160 CHAPTER 7 ADVANCED JAVASCRIPT FUNCTIONAL PROGRAMMING AND CLASS-BASED OOP function alertThreeThings a b c alert a alert b alert c var alertTwoThings alerted first alertTwoThings foo bar alerts alerted first alerts foo alerts bar We ve just defined a function that if we were to write it out ourselves would behave like this function alertTwoThings b c return alertThreeThings alerted first b c But by using curry we re able to express this more concisely and flexibly. Function curry can accept any number of arguments. I could load two or .

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
Đã 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.