Javascript Object-oriented programming (i): encapsulation by Ruan Yi Feng

Source: Internet
Author: User
Tags hasownproperty

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

They are excellent 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 parts of the discussion "Inheritance" (inheritance).

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

Javascript Object-oriented programming (i): encapsulation

Nanyi

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

So, what should we do if we want to encapsulate the property and method as an object and even generate an instance object from the prototype object?

First, the original mode of the generated object

Suppose we think of a cat as an object that has two properties of "name" and "Color".

var Cat = {

Name: ",

Color: '

}

Now we need to generate two instance objects based on the schema of the prototype object.

var cat1 = {}; Create an empty object

Cat1.name = "Mao"; Assigning values according to the properties of the prototype object

Cat1.color = "Yellow";

var cat2 = {};

Cat2.name = "Er mao";

Cat2.color = "BLACK";

Well, this is the simplest package, encapsulating two attributes in an object. However, there are two shortcomings in this writing, one is that if you generate several instances, it is very troublesome to write, and the other is that there is no way between the example and the prototype, and we can see what the connection is.

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 generate the instance object, which is equivalent to calling the function:

var cat1 = Cat ("Da Mao", "Yellow");

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

The problem with this approach remains that there is no intrinsic connection between CAT1 and CAT2, and it does not reflect that they are instances of the same prototype object.

Third, the structural function mode

To solve the problem of generating instances from prototype objects, JavaScript provides a constructor (Constructor) pattern.

The so-called "constructor" is actually a normal function, but the this variable is used internally. Using the new operator on a constructor enables you to generate an instance, and the this variable is bound to the instance object.

For example, a cat's prototype object can now be written like this,

function Cat (name,color) {

This.name=name;

This.color=color;

}

We can now build the instance object.

var cat1 = new Cat ("Da Mao", "Yellow");

var cat2 = new Cat ("Er Mao", "Black");

alert (cat1.name); Da Mao

alert (Cat1.color); Yellow

At this point, 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 validates 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 structure function pattern

The constructor method works well, but there is a problem of wasting memory.

See, we now add a constant property "type" for the Cat object, and then add a method eat (Eat mouse). So, the prototype object cat becomes the following:

function Cat (name,color) {

THIS.name = name;

This.color = color;

This.type = "Cat animal";

This.eat = function () {alert ("Eat Mouse");

}

The same approach is used to generate an instance:

var cat1 = new Cat ("Da Mao", "Yellow");

var cat2 = new Cat ("Er Mao", "Black");

alert (Cat1.type); Cat Animals

Cat1.eat (); Eat mice

There seems to be no problem on the surface, but there is a big drawback in actually doing so. That is, for each instance object, the type attribute and the Eat () method are identical, and each time an instance is generated, it must be a duplicate of the content and occupy more memory. This is neither environmentally friendly nor inefficient.

Alert (cat1.eat = = cat2.eat); False

Can the type attribute and the Eat () method be generated only once in memory, and then all instances point to that memory address? The answer is yes.

Five, prototype mode

JavaScript specifies that each constructor has a prototype property that points to another object. All properties and methods of this object are inherited by an 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 animal";

Cat.prototype.eat = function () {alert ("Eat Mouse")};

Then, build the instance.

var cat1 = new Cat ("Da Mao", "Yellow");

var cat2 = new Cat ("Er Mao", "Black");

alert (Cat1.type); Cat Animals

Cat1.eat (); Eat mice

At this point the type attribute and the Eat () method for all instances are actually the same memory address, pointing to the prototype object, thus improving the efficiency of the operation.

Alert (cat1.eat = = cat2.eat); True

Six, the verification method of prototype mode

To match the prototype property, 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 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 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 properties of an object.

For (Var prop in cat1) {alert ("cat1[" +prop+ "]=" +cat1[prop]);}

Javascript Object-oriented programming (i): encapsulation by Ruan Yi Feng

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.