Học JavaScript qua ví dụ part 24

Thêm biện pháp khác với nguyên mẫu JavaScript phương pháp chỉ là tài sản đã được phân công chức năng cho các giá trị của họ. Cách sử dụng chung cho các nguyên mẫu là để mở rộng một lớp học bằng cách cho nó phương pháp mới. | 202 Chapter 8 Objects Figure Going up the prototype chain. Adding Methods with Prototype JavaScript methods are just properties that have been assigned functions for their values. A common use for prototypes is to extend a class by giving it new methods. You can use a prototype to assign methods that are common to all objects in a given class. The benefit of using the prototype is that the method does not have to be created and initialized every time an object is created and there is no duplication of function code. All objects in the class share the same prototype method. In Example a new method is defined for the Book class to add a tax to the price of each book. All Book objects will have access to this method. EXAMPLE html head title Method Inheritance title script type text javascript 1 function Book title author price The Book constructor title Book properties attributes author price 2 showProps Book method 3 function showProps var result for var i in this result i this i br return result script head body script type text javascript Add a new method with prototype From the Library of Extending Objects with Prototypes 203 EXAMPLE 4 function addTax return 2 5 var famousBook new Book War and Peace Leo Tolstoy var myBook new Book JavaScript by Example Ellie Quigley 25 6 br b br br b br 7 With tax costs . br With tax costs 8 . br script body html EXPLANATION 1 The constructor function called Book defines the properties and methods for a Book class. Book is a JavaScript representation of a class. The constructor function has a prototype object containing those properties that are inherited by all Book objects. 2 A function called showProps is defined on line 3. Its name

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
109    308    1    14-05-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.