Javascript Object-Oriented Programming (1) Encapsulation

Source: Internet
Author: User
Tags hasownproperty

LearningJavascriptWhat is the most difficult part?

I think Object objects) are the most difficult. Because the Object model of Javascript is unique and different from other languages, it is difficult for beginners to master.

The following is my study notes. I hope it will help you to learn this part. I have primarily referred to the Object-Oriented JavaScript and Professional JavaScript for Web Developers (2nd Edition) books. They are all excellent Javascript books and are recommended for reading.

Note is divided into two parts. The first part of today is to discuss "Encapsulation" Encapsulation). The second part is to discuss "Inheritance" Inheritance ).

JavascriptIs an object-based language. Almost everything you encounter is an object. However, it is not a real object-oriented programming language (OOP), because its syntax does not contain class classes ).

So what should we do if we want to encapsulate "property" property) and "method" method) into an object or even generate an instance object from the prototype object?

1. original object generation mode

Suppose we regard a cat as an object, which has two attributes: "name" and "color.

 
 
  1. var Cat = {  
  2. name : '',  
  3. color : '' 
  4. }  

Now, we need to generate two instance Objects Based on this prototype object.

 
 
  1. Var cat1 = {};
  2. Cat1.name = "Mao ";
  3. Cat1.color = "yellow ";
  4. Var cat2 = {};
  5. Cat2.name = "ermao ";
  6. Cat2.color = "black ";

Well, this is the simplest encapsulation. However, this method has two disadvantages: one is that if several instances are generated more, it will be very difficult to write; the other is that there is no way between the instance and the prototype, so we can see what the relationship is.

2. improvements to the original mode

We can write a function to solve the problem of code duplication.

 
 
  1. function Cat(name,color){  
  2. return {  
  3. name:name,  
  4. color:color  
  5. }  
  6. }  

Then, the instance object is generated, so the function is called:

 
 
  1. Var cat1 = Cat ("hairy", "yellow ");
  2. Var cat2 = Cat ("ermao", "black ");

The problem with this method is that there is no internal connection between cat1 and cat2, and it cannot reflect that they are instances of the same prototype object.

3. constructor Mode

To solve the problem of generating instances from a prototype object, Javascript provides a Constructor mode.

The so-called "constructor" is actually a common function, but this variable is used internally. You can use the new operator to generate an instance for the constructor, and this variable is bound to the instance object.

For example, the prototype object of a cat can now be written like this,

 
 
  1. function Cat(name,color){  
  2. this.name=name;  
  3. this.color=color;  
  4. }  

Now we can generate instance objects.

 
 
  1. Var cat1 = new Cat ("Da Mao", "yellow ");
  2. Var cat2 = new Cat ("two hairs", "black ");
  3. Alert (cat1.name); // damao
  4. Alert (cat1.color); // yellow

At this time, cat1 and cat2 will automatically contain a constructor attribute pointing to their constructor.

 
 
  1. alert(cat1.constructor == Cat); //true  
  2. alert(cat2.constructor == Cat); //true 

Javascript also provides an instanceof operator to verify the relationship between the prototype object and the instance object.

 
 
  1. alert(cat1 instanceof Cat); //true  
  2. alert(cat2 instanceof Cat); //true  

4. constructor mode Problems

The constructor method is very useful, but there is a waste of memory.

Please see, we now add a constant property "type" for the Cat object), and then add a method to eat mouse eat ). Then, the prototype Cat is changed to the following:

 
 
  1. Function Cat (name, color ){
  2. This. name = name;
  3. This. color = color;
  4. This. type = "cat ";
  5. This. eat = function () {alert ("eat mouse ");};
  6. }

Use the same method to generate an instance:

 
 
  1. Var cat1 = new Cat ("Da Mao", "yellow ");
  2. Var cat2 = new Cat ("two hairs", "black ");
  3. Alert (cat1.type); // cat
  4. Cat1.eat (); // eat mouse

It seems that there is no problem on the surface, but in fact there is a huge drawback in doing so. That is, for each instance object, the type attribute and the eat () method are the same content. Each time an instance is generated, it must be duplicated content, occupying more memory. This is neither environmentally friendly nor efficient.

 
 
  1. alert(cat1.eat == cat2.eat); //false 

Can I have the type attribute and the eat () method be generated only once in the memory, and then all instances point to that memory address? The answer is yes.

5. Prototype mode

Javascript requires that each constructor has a prototype attribute pointing to another object. All attributes and methods of this object will be inherited by the constructor instance.

This means that we can directly define the unchanged attributes and methods on the prototype object.

 
 
  1. Function Cat (name, color ){
  2. This. name = name;
  3. This. color = color;
  4. }
  5. Cat. prototype. type = "Cat ";
  6. Cat. prototype. eat = function () {alert ("eat mouse ")};

Then, generate the instance.

 
 
  1. Var cat1 = new Cat ("Da Mao", "yellow ");
  2. Var cat2 = new Cat ("two hairs", "black ");
  3. Alert (cat1.type); // cat
  4. Cat1.eat (); // eat mouse

In this case, the type attribute and the eat () method of all instances are actually a memory address pointing to the prototype object, which improves the running efficiency.

 
 
  1. alert(cat1.eat == cat2.eat); //true  

6. Prototype verification method

6.1 isPrototypeOf ()

This method is used to determine the relationship between a proptotype object and an instance.

 
 
  1. alert(Cat.prototype.isPrototypeOf(cat1)); //true  
  2. alert(Cat.prototype.isPrototypeOf(cat2)); //true  

6.2 hasOwnProperty ()

Each instance object has a hasOwnProperty () method to determine whether an attribute is a local attribute or inherited from a prototype object.

 
 
  1. alert(cat1.hasOwnProperty("name")); // true  
  2. alert(cat1.hasOwnProperty("type")); // false  

6.3 in Operator

The in operator can be used to determine whether an instance contains an attribute, whether it is a local attribute or not.

 
 
  1. alert("name" in cat1); // true  
  2. alert("type" in cat1); // true 

The in operator can also be used to traverse all attributes of an object.

 
 
  1. for(var prop in cat1) { alert("cat1["+prop+"]="+cat1[prop]); }  

Hope to help you.

Original article address:Http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html

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.