Mở rộng đối tượng với nguyên mẫu Trong ngôn ngữ hướng đối tượng, giống như Java và C + +, đối tượng, cùng với các thuộc tính của nó (nhà nước) và phương pháp (hành vi), được tích hợp sẵn vào trong thùng chứa được gọi là một lớp. Các ngôn ngữ lập trình tất cả các lớp học cho phép tái sử dụng và mở rộng một lớp học hiện có; đó là, kế thừa thường được sử dụng nhà nước và hành vi từ các lớp khác | 196 Chapter 8 Objects Figure The book object s properties. Extending Objects with Prototypes In object-oriented languages like Java and C the object along with its properties state and methods behavior is bundled up into a container called a class. These programming languages all allow classes to reuse and extend an existing class that is inherit commonly used state and behaviors from other classes. A new class called a subclass can be derived from an existing class. For example if you have a Pet class let s say all pets have an owner a gender and some methods for setting and getting the properties. We could create subclasses of the Pet such as a Dog and Cat because both the Dog and Cat share the same properties as a Pet. The code for the Pet can be extended to the Dog and the Cat by using inheritance. Then each subclass can be refined further by adding its own specific features. Let s look at an example of how JavaScript might use inheritance. A constructor function called divStyle has been defined. It will be used to create div containers to style a Web page. The constructor defines the properties for a div for example the borders padding background color and so on and has a divGet method to display the div in the document. Later we want to make divStyle objects but change or add properties perhaps change the width of the border or set a border color. We can reuse or extend the divStyle code by using inheritance. Section explained that unlike Java and C JavaScript doesn t have a class mechanism per se but inheritance involves reusing or extending a class. With JavaScript we can simulate a class with a constructor function and the new keyword. And to implement inheritance JavaScript extends a the class with a prototype. For those of you who are Java or C programmers JavaScript does not use keywords like extended protected private public etc. . How does prototype inheritance work JavaScript functions are automatically given an empty prototype object. .