Home >Web Front-end >JS Tutorial >Javascript object-oriented programming (1) encapsulation_js object-oriented

Javascript object-oriented programming (1) encapsulation_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:03:01814browse

What’s the hardest part about learning Javascript?

I think Object is the hardest. Because the Object model of Javascript is very unique and different from other languages, it is not easy for beginners to master.

The following are my study notes. I hope it will be helpful to everyone in studying this part. I mainly referred to
the following two books:

Javascript object-oriented programming (1) encapsulation_js object-oriented

《Object-Oriented Javascript》(Object-Oriented JavaScript)

Javascript object-oriented programming (1) encapsulation_js object-oriented

《Javascript Advanced Programming (Second Edition)》(Professional JavaScript for Web Developers, 2nd Edition)

They are all excellent Javascript books and are recommended reading.

The note is divided into three parts. The first part today is about "Encapsulation", and the second part and the third part will discuss "Inheritance".

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

Javascript Object-Oriented Programming (1): Encapsulation

Author: Ruan Yifeng

Javascript is an object-based language, and almost everything you encounter is an object. However, it is not a true object-oriented programming (OOP) language because there is no class in its syntax.

So, 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. Generate the original mode of the object

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

Copy code The code is as follows:

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

Now, we need to generate two instance objects based on this prototype object.
Copy code The code is as follows:

 var cat1 = {}; // Create an empty object
 cat1.name = "大马"; // Assign values ​​according to the attributes of the prototype object
 cat1.color = "yellow";
 var cat2 = {};
 cat2.name = "Ermao";
 cat2.color = "Black";

Okay, this is the simplest encapsulation. However, this way of writing has two disadvantages. First, if more instances are generated, it will be very troublesome to write; second, there is no way to see the connection between the instances and the prototype.
2. Improvement of the original mode
We can write a function to solve the problem of code duplication.
Copy code The code is as follows:

function Cat(name,color){
return {
                                                                   in in in us in us in us in us in us in us can in us us can may may us may may may on in in: 🎜>

Copy code

The code is as follows:

In order to solve the problem of generating instances from prototype objects, Javascript provides a constructor pattern.
The so-called "constructor" is actually an ordinary function, but the this variable is used internally. Using the new operator on the constructor will generate an instance, and the this variable will be bound to the instance object.
For example, the cat prototype object can now be written like this,


Copy the code

The code is as follows:

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

We can generate it now instance object.
Copy code The code is as follows:

 var cat1 = new Cat("Big Hair","Yellow ");
var cat2 = new Cat("二毛","black");
alert(cat1.name); // Big Cat
alert(cat1.color); // Yellow

At this time, cat1 and cat2 will automatically contain a constructor attribute pointing to their constructor.
Copy code 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.
Copy code The code is as follows:

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

4. Problems with the constructor pattern
The constructor method is easy to use, but there is a problem of wasting memory .
Please see, we now add an immutable attribute "type" (type) to the Cat object, and then add a method eat (eat mice). Then, the prototype object Cat becomes as follows:
Copy code The code is as follows:

function Cat(name,color){
This.name = name;
this.color = color;
this.type = "Feline";
this.eat = function(){ alert("Eat mice");};
 }

Use the same method to generate an instance:
Copy code The code is as follows:

var cat1 = new Cat("Big Hair","Yellow");
var cat2 = new Cat ("Er Hair","Black" ");
 alert(cat1.type); // Cats
 cat1.eat(); // Eating mice

On the surface there seems to be no problem, but in fact Do, there is a big drawback. That is, for each instance object, the type attribute and eat() method have exactly the same content. Every time an instance is generated, it must occupy more memory for repeated content. This is neither environmentally friendly nor efficient.
 alert(cat1.eat == cat2.eat); //false
Can the type attribute and eat() method be generated only once in memory, and then all instances point to that memory address? The answer is yes.
5. Prototype mode
Javascript stipulates that each constructor has a prototype attribute that points to another object. All properties and methods of this object will be inherited by the instance of the constructor.
This means that we can define those immutable properties and methods directly on the prototype object.
Copy code The code is as follows:

function Cat(name,color){
this .name = name;
This.color = color;
}
Cat.prototype.type = "Feline";
Cat.prototype.eat = function(){alert("Eat Mouse")};

Then, generate the instance.
Copy code The code is as follows:

 var cat1 = new Cat("Big Hair","Yellow ");
var cat2 = new Cat("二毛","黑");
alert(cat1.type); // Cats
cat1.eat(); // Eat mice

At this time, the type attribute and eat() method of all instances are actually the same memory address, pointing to the prototype object, thus improving operating efficiency.
 alert(cat1.eat == cat2.eat); //true
6. Prototype mode verification method
6.1 isPrototypeOf()
This method is used to determine, The relationship between a certain proptotype object and an instance.
Copy code 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, which is used to determine whether a certain property is a local property or a property inherited from the prototype object.
Copy code The code is as follows:

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

6.3 in operator
in operator can be used to determine whether an instance contains An attribute, whether local or not.
Copy code 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 properties of an object.
 for(var prop in cat1) { alert("cat1[" prop "]=" cat1[prop]); }
Not finished yet, please continue reading the second part of this series " Constructor Inheritance " and the third part "Inheritance of non-constructor functions ".

(End)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn