Learning Javascript Object-Oriented Programming encapsulation and javascript object-oriented

Source: Internet
Author: User
Tags hasownproperty

Learning Javascript Object-Oriented Programming encapsulation and javascript object-oriented

Javascript is an object-based language. Almost everything you encounter is an object. However, it is not a real Object-Oriented Programming (OOP) language, because its syntax does not contain class ).
If we want to encapsulate "property" and "method" into an object, or even generate an instance object from the prototype object, what should we do?
1. original object generation mode
Suppose we regard a cat as an object, which has two attributes: "name" and "color.

var Cat = {    name : '',    color : ''  }

Now, we need to generate two instance objects according to the schema of the prototype object.

Var cat1 ={}; // create an empty object cat1.name = ""; // assign cat1.color = "yellow" according to the attributes of the prototype object; var cat2 = {}; cat2.name = "ermao"; cat2.color = "black ";

Well, this is the simplest encapsulation. Two attributes are encapsulated in an object. 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.
Ii. improvements to the original model
We can write a function to solve the problem of code duplication.

function Cat(name,color){    return {      name:name,      color:color    }  }

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

Var cat1 = Cat ("", "yellow"); var cat2 = Cat ("", "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.
Iii. 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,
 

 function Cat(name,color){    this.name=name;    this.color=color;  }

Now we can generate instance objects.

Var cat1 = new Cat ("", "yellow"); var cat2 = new Cat ("", ""); alert (cat1.name ); // hairy alert (cat1.color); // yellow

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

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

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

 alert(cat1 instanceof Cat); //true  alert(cat2 instanceof Cat); //true

Iv. constructor Mode
The constructor method is very useful, but there is a waste of memory.
Please see, now we add a constant attribute "type" (type) for the Cat object, and then add a method eat (eat mouse ). Then, the prototype Cat is changed to the following:

Function Cat (name, color) {this. name = name; this. color = color; this. type = "cat"; this. eat = function () {alert ("eat mouse ");};}

Use the same method to generate an instance:

Var cat1 = new Cat ("", "yellow"); var cat2 = new Cat ("", ""); alert (cat1.type ); // 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.

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.
V. 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:

Function Cat (name, color) {this. name = name; this. color = color;} Cat. prototype. type = "Cat"; Cat. prototype. eat = function () {alert ("eat mouse ")};

Then, generate the instance.

Var cat1 = new Cat ("", "yellow"); var cat2 = new Cat ("", ""); alert (cat1.type ); // cat1.eat (); // eat mouse

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

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

Vi. Prototype mode Verification Method
To work with the prototype attribute, Javascript defines some helper methods to help us use them .,
6.1 isPrototypeOf ()
This method is used to determine the relationship between a proptotype object and an instance.

 alert(Cat.prototype.isPrototypeOf(cat1)); //true  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.

 alert(cat1.hasOwnProperty("name")); // true  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.

 alert("name" in cat1); // true  alert("type" in cat1); // true

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

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

The above is all about javascript encapsulation, and I hope it will help you learn it.

Articles you may be interested in:
  • Javascript encapsulation source code for an AJAX Automatic completion function [Chinese supported]
  • A js encapsulated good tab effect code
  • Class Of Marquee Scroll general non-stop rolling JS encapsulation Class
  • JS class encapsulation and implementation code
  • Simple encapsulation of js data verification set, js email verification, js url verification, js length verification, and js digital verification
  • Javascript paging Based on jquery Encapsulation
  • How to encapsulate jQuery classes and plug-ins into seajs modules
  • Jquery automatically encapsulates form into json
  • Use native js to encapsulate the sliding effect of webapp (Inertial sliding and sliding rebound)
  • Encapsulation instance of touch events in Web development of javascript mobile devices

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.