JavaScript Object-Oriented Programming: Prototype inheritance instances

Source: Internet
Author: User

JavaScript is not a pure object-oriented language, but an object-based language. Object Inheritance is inherited in the form of prototype functions, the following is a small example of writing an object-oriented programming model using JavaScript.

Introduction to the simulation of object-oriented technology in JavaScript

Create base class

First, we need to create a base class to instantiate the operation. The identifier after New is the constructor of the object. Any javascript class can create such an instance. For example, the following code creates a person class and instantiates a person object.

 
 
  1. function Person(first, last) {  
  2.   this.first = first;  
  3.   this.last = last;  
  4.  }  
  5.  var person = new Person(“John”, “Dough”); 

Add Method

If you want to add a method to the class to operate on the instance of this class, just like this, we can create a "toString" method to display the content of the object. This is implemented on our base class.

 
 
  1. Person.prototype.toString = function() {  
  2.   return this.first + ” ” + this.last;  
  3.  };  
  4.  alert( person ); // displays “John Dough” 

This proves a feature of the JavaScript language, "prototype ". Simply put, all JavaScript objects have a private prototype attribute (_ proto _). This "private" means this property is invisible or only the object itself can be accessed. When an object is searched for a property, it first finds whether the property exists in the instance. If not, it searches for the property on the "private" prototype of the object. The prototype can have its own private prototype, so the query can continue to run along the prototype chain until the property is found or it is still not found when it reaches the empty private prototype.

Create subclass

Return to the person object. At this time, we need to add more information to make the person look like a subject. So, Let's define it like this.

 
 
  1. KevLinDev.extend = function(subClass, baseClass) {  
  2.  
  3.    function inheritance() {}  
  4.    inheritance.prototype = baseClass.prototype;  
  5.    subClass.prototype = new inheritance();  
  6.    subClasssubClass.prototype.constructor = subClass;  
  7.    subClass.baseConstructor = baseClass;  
  8.    subClass.superClass = baseClass.prototype;  
  9.  
  10. }  
  11.  
  12. function Employee(first, last, id) {  
  13.  
  14.     // initialize properties here  
  15.  
  16. }  
  17.  
  18. KevLinDev.extend(Employee, Person); 

We first created a convenient function to set our inheritance chain. We need to make the attributes of baseclass equal to those of subclass. Remember, when we call "new", the prototype property will be copied to "_ proto" of an instance, and the inheritance chain will be connected ). However, we cannot allow both the subClass and baseClass prototype to point to the same object. It seems that it is better to add a method to baseClass and then add this method to subClass at the same time.

However, if you add a method to subClass, baseClass also adds the corresponding method. Obviously it is not the way we want to handle it. We need a way to disconnect two prototypes but allow subClass to inherit the baseClass method. At this time, we need the help of the prototype chain.

First, we need to define a function called "inheritance" nesting. Then, we direct the prototype to the baseClass prototype. In this way, any new "inheritance" instance has its own "_ proto _", which refers to the prototype of the base class. Finally, we create an "inheritance" instance and assign it to the subClass prototype. Now we need to create a new subClass instance. The "_ proto _" of this instance will point to the "inheritance" instance. The private prototype of the "inheritance" instance refers to the public prototype of the base class.

In this way, the changes to the baseClass prototype will affect the subClass instance through the inheritance chain. Because we have created a new object for the subclass prototype attribute, we can add it to the subclass prototype without affecting the prototype of the base class. (Xiao Hao added: because the "_ proto _" of the subClass we create now directs to the "inheritance" instance. If subclass. prototype = baseClass. prototype; then, the corresponding method will be added to the base class when adding methods to the subclass)

Each time you create a new object instance, the Constructor of the instance points to the Constructor used for instantiation (<instance>. Constructor = <object> ). I will compare an instance with the constructor property of a function to test the type of Object Instantiation. Call new inheritance () to direct the subclass prototype constructor to the inheritance function that will corrupt my tests. I can update the constructor attribute to point to the subclass constructor to fix this problem.

The final two rows are treated as convenient attributes for calling the ancestor constructor and method. This code is needed in the next part.

Call base class

We have defined a new subclass, but we still need to initialize it properly. Ideally, we should not copy the code from person to subclass or employee. We need to find a better way to pass the "first" and "last" parameters to the Person, so that the employee can process the id parameters by himself. The following is the implementation method:

 
 
  1. function Employee(first, last, id) {  
  2.   Employee.baseConstructor.call(this, first, last);  
  3.   this.id = id;  
  4.   this.add = function(){alert(“add success”)}  
  5.  }  
  6.  
  7. KevLinDev.extend(Employee, Person); 

It is undeniable that it is a little ugly. However, we call the base class method through "call. This calls the base class constructor, just like the previous "this ". The remaining parameters are passed to the called function. In this case, the constructors of the base class will execute any processing method on "first" and "last. The Employee constructor processes "id ".

Create a subclass

I have discovered that an oop mode has been built to support inheritance of one level rather than two or more levels. Let's create another subclasses to determine that our concept is appropriate.

 
 
  1. function Manager(first, last, id, department) {  
  2.   Manager.baseConstructor.call(this, first, last, id);  
  3.   this.department = department;  
  4.  }  
  5.  
  6. KevLinDev.extend(Manager, Employee); 

Nothing new. The code looks similar to the definition of our employee and shows that inheritance is working properly.

Link: http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.