Learn JavaScript encapsulation _javascript techniques for object-oriented programming

Source: Internet
Author: User
Tags hasownproperty

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?
First, the original mode of the generated object
Suppose we look at a cat as an object, it has two attributes of "first name" and "Color".

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

Now, we need to generate two instance objects based on the specification (schema) of this prototype object.

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

OK, so this is the simplest package, which encapsulates two attributes in one object. 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.
Ii. Improvement of the original model
we can write a function that solves the problem of code duplication.

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

Then the instance object is generated, which is tantamount to calling the function:

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.
third, the constructor function 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,
 

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

We can now generate the instance object.

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

Then CAT1 and Cat2 automatically contain a constructor attribute that points to their constructors.

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.

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

Four, 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:

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:

var cat1 = new Cat ("hairy", "yellow");
var cat2 = new Cat ("Er Mao", "Black");
alert (Cat1.type); Cat
Cat1.eat ()//eating 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.
Five, 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:

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

Then, the instance is generated.

var cat1 = new Cat ("hairy", "yellow");
var cat2 = new Cat ("Er Mao", "Black");
alert (Cat1.type); Cat
Cat1.eat ()//eating 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

Vi. verification method of prototype mode
To match the prototype attribute, JavaScript defines some helper methods that help us to use it. ,
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 that is used to determine whether a property is a local property or a property that inherits 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 a property, whether it is a local property or not.

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));

The above is about the full content of JavaScript package, I hope to help you learn.

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.