May mắn thay, JavaScript là cực kỳ linh hoạt, làm cho nó dễ dàng để thêm các tính năng này. Trong chương này, chúng ta nhìn vào các ngôn ngữ hướng đối tượng khác thực hiện các giao diện, và cố gắng để cạnh tranh với những tính năng tốt nhất của mỗi. Chúng tôi nhìn vào một số cách để làm điều này trong JavaScript, | CHAPTER 5 THE SINGLETON PATTERN 69 method2 function Initialization method. init function Invoke the initialization method after the page loads. addLoadEvent To explain how this can be used let s take a fairly common task in web development and walk through it. Often it is desirable to add functionality to a form with JavaScript. In order to degrade gracefully the page is usually created first as a normally submitting JavaScript-free HTML-only experience. Then the form action is hijacked using JavaScript to provide additional features. Here is a singleton that will look for a specific form and hijack it RegPage singleton page handler object. Constants. FORM_ID reg-form OUTPUT_ID reg-results Form handling methods. handleSubmit function e Stop the normal form submission. var data var inputs input Collect the values of the input fields in the form. for var i 0 len i len i data inputs i .name inputs i .value Send the form values back to the server. data sendRegistration function data Make an XHR request and call displayResult when the response is received. . 70 CHAPTER 5 THE SINGLETON PATTERN displayResult function response Output the response directly into the output element. We are assuming the server will send back formatted HTML. response Initialization method. init function Get the form and output elements. Hijack the form submission. addEvent submit Invoke the initialization method after the page loads. addLoadEvent We are first assuming that the GiantCorp namespace has already been created as an empty object literal. If it hasn t this first line will cause an error. This error can be prevented