Javascript Object-oriented programming (i) encapsulation _js object-oriented

Source: Internet
Author: User
Tags inheritance hasownproperty

What are the hardest places to learn about JavaScript?

I think the object is the hardest. Because the object model of JavaScript is unique and is different from other languages, beginners are not easy to master.

The following is my study notes, I hope to learn this part of help. I have mainly consulted
The following two books:

Object-oriented JavaScript (object-oriented JavaScript)

"JavaScript Advanced Programming (Second Edition)" (Professional JavaScript for WEB developers, 2nd Edition)

They are very good javascript readings and are recommended for reading.

The notes are divided into three parts. The first part of today is the discussion of "encapsulation" (encapsulation), followed by the second and third sections of the discussion "Inheritance" (inheritance).

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

Javascript Object-oriented programming (i): encapsulation

Author: Ruan Yi Feng

JavaScript is an object-based (object-based) language, and almost all of the things you encounter are objects. However, it is not a true object-oriented programming (OOP) language because its syntax has no class (class).

So what should we do if we're going to encapsulate the property and method (methods) into an object and even generate an instance object from a prototype object?

1. Generate the original schema of the object

Suppose we look at a cat as an object, it has two attributes of "first name" and "Color".

Copy Code code as follows:

var Cat = {
Name: ',
Color: "
}

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

var cat1 = {}; Create an empty object
Cat1.name = "hairy"; Assigning values to the properties of a prototype object
Cat1.color = "Yellow";
var cat2 = {};
Cat2.name = "Er mao";
Cat2.color = "BLACK";

Well, that's the simplest package. However, there are two disadvantages to this writing, one is that if you generate more than a few instances, it is very troublesome to write, and the second is between the example and the prototype, there is no way to see what connection.
2. Improvements to the original model
We can write a function that solves the problem of code duplication.
Copy Code code as follows:

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

Then the instance object is generated, which is tantamount to calling the function:
Copy Code code as follows:

var cat1 = Cat ("hairy", "yellow");
var cat2 = Cat ("Er Mao", "Black");

The problem with this approach remains that there is no intrinsic connection between CAT1 and CAT2 and that they are not examples of the same archetypal object.
3. Constructor pattern
To solve the problem of generating an instance from a prototype object, JavaScript provides a constructor (constructor) pattern.
The so-called "constructor", in fact, is a normal function, but the internal use of the this variable. The new operator is used on the constructor to generate an instance, and the this variable is bound to the instance object.
For example, a cat's archetypal object can now be written like this,
Copy Code code as follows:

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

We can now generate the instance object.
Copy Code code as follows:

var cat1 = new Cat ("hairy", "yellow");
var cat2 = new Cat ("Er Mao", "Black");
alert (cat1.name); Nagymaros
alert (Cat1.color); Yellow

Then CAT1 and Cat2 automatically contain a constructor attribute that points to their constructors.
Copy Code code as follows:

Alert (Cat1.constructor = = Cat); True
Alert (Cat2.constructor = = Cat); True

JavaScript also provides a instanceof operator that verifies the relationship between a prototype object and an instance object.
Copy Code code as follows:

Alert (cat1 instanceof Cat); True
Alert (cat2 instanceof Cat); True

4. The problem of the constructor pattern
The constructor method works fine, but there is a problem with wasting memory.
See, we now add a invariant property "type" to the Cat object and add a method eat (eat the mouse). So, the prototype object cat becomes the following:
Copy Code code as follows:

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

Or do you use the same method to generate an instance:
Copy Code code as follows:

var cat1 = new Cat ("hairy", "yellow");
var cat2 = new Cat ("Er Mao", "Black");
alert (Cat1.type); Cat Family Animal
Cat1.eat (); Eat mice

There seems to be no problem on the surface, but in practice there is a big drawback. That is, for each instance object, the type attribute and the Eat () method are exactly the same, and each time an instance is generated, it must be duplicated, consuming some more memory. This is neither environmental protection nor efficiency.
Alert (cat1.eat = = cat2.eat); False
Can I have the type attribute and the Eat () method generate only once in memory, and then all instances point to that memory address? The answer is OK.
5. Prototype mode
JavaScript stipulates that each constructor has a prototype attribute that points to another object. All of the properties and methods of this object are inherited by the instance of the constructor.
This means that we can define the invariant properties and methods directly on the prototype object.
Copy Code code as follows:

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

Then, the instance is generated.
Copy Code code as follows:

var cat1 = new Cat ("hairy", "yellow");
var cat2 = new Cat ("Er Mao", "Black");
alert (Cat1.type); Cat Family Animal
Cat1.eat (); Eat mice

The type attribute and the Eat () method of all instances are in fact the same memory address, pointing to the prototype object, thus increasing the efficiency of the operation.
Alert (cat1.eat = = cat2.eat); True
6. Verification method of prototype mode
6.1 isprototypeof ()
This method is used to determine the relationship between a Proptotype object and an instance.
Copy Code code as follows:

Alert (Cat.prototype.isPrototypeOf (CAT1)); True
Alert (Cat.prototype.isPrototypeOf (CAT2)); True

6.2 hasOwnProperty ()
Each instance object has a hasOwnProperty () method that is used to determine whether a property is a local property or a property that inherits from a prototype object.
Copy Code code 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 a property, whether it is a local property or not.
Copy Code code as follows:

Alert ("name" in CAT1); True
Alert ("type" in CAT1); True

The in operator can also be used to traverse all the properties of an object.
For (Var prop in cat1) {alert ("cat1[" +prop+ "]=" +cat1[prop));
Before you finish, read the second part of the series, "Inheritance of constructors" and Part III, "Inheritance of non-constructors."

Finish

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.