Javascript Object-Oriented Programming (1) Encapsulation _ js object-oriented-js tutorial

Source: Internet
Author: User
Tags hasownproperty
In my opinion, 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.

What is the most difficult part of learning Javascript?

In my opinion, 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. My main reference
The following two books:

Object-Oriented Javascript)

Professional Javascript for Web Developers, 2nd Edition)

They are all excellent Javascript books and are recommended for reading.

Note is divided into three parts. The first part of today is to discuss "Encapsulation" (Encapsulation). The second and third sections will discuss "Inheritance" (Inheritance ).

======================================

Javascript Object-Oriented Programming (1): Encapsulation

Author: Ruan Yifeng

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.

The Code is as follows:


Var Cat = {
Name :'',
Color :''
}


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

The Code is as follows:


Var cat1 = {}; // create an empty object
Cat1.name = ""; // assign values based on the properties of the prototype object
Cat1.color = "yellow ";
Var cat2 = {};
Cat2.name = "ermao ";
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.

The Code is as follows:


Function Cat (name, color ){
Return {
Name: name,
Color: color
}
}


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

The Code is as follows:


Var cat1 = Cat ("hairy", "yellow ");
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,

The Code is as follows:


Function Cat (name, color ){
This. name = name;
This. color = color;
}


Now we can generate instance objects.

The Code is as follows:


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


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

The Code is as follows:


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.

The Code is as follows:


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


4. constructor mode Problems
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:

The Code is as follows:


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:

The Code is as follows:


Var cat1 = new Cat ("Da Mao", "yellow ");
Var cat2 = new Cat ("two hairs", "black ");
Alert (cat1.type); // cat
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.
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.

The Code is as follows:


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.

The Code is as follows:


Var cat1 = new Cat ("Da Mao", "yellow ");
Var cat2 = new Cat ("two hairs", "black ");
Alert (cat1.type); // cat
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
6. Prototype verification method
6.1 isPrototypeOf ()
This method is used to determine the relationship between a proptotype object and an instance.

The Code is as follows:


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.

The Code is as follows:


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.

The Code is as follows:


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]);}
Before completion, please continue to read the second part of this series, "inheritance of constructor" and the third part, "inheritance of non-constructor".

(End)

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.