The use of encapsulation in JavaScript instance tutorials

Source: Internet
Author: User

Today, we talk about packaging stars in JavaScript design patterns --encapsulation, we will abstract some things in reality into a Class and take the attributes of things (nouns) as Class of the Property take the action (verb) of a thing as Class of the Methods . In object-oriented languages (C # , and so on) there are some keywords to decorate classes or attributes (Private, Public , Protect ), these keywords describe the access permissions, do not explain more.

Let's take a look at the variable characteristics of Javascript (we also use the last example):

var mans = function (name, age) {

This. name = name;

This. Age = age;

}

var person = new Interface ("person", ["GetName", "getage"]);

Man.prototype = {Getname:function () {return this. Name; },

Getage:function () {return this. Age; }

}

var Alan = new Man ("Alan", 25);

Alert (Alan.getage ());

Alan.displayall = function () {return ' Name: ' +this. GetName () + "; Age: ' + this. Getage ()}

Alert (Alan.displayall ());

I first created a Class(an anonymous method for Javascript) with 2 public ) field (this blog will explain in detail, continue to look down) and 2 Public methods, we created a Instance--alan , but I can do it for this Instance dynamically add a Displayall method, I think any object-oriented language is not going to do this, Javascript one of the flexible embodiment.

We now assume a scenario where, if a lot of programmers want to use this code, because of the variability of Javascript, programmers can change the value of Name after instantiation, The initialized action is meaningless:

var Alan = new Man ("Alan", 25);

Alan.name = "Alice"; tragedy, I became Alice when I was alert.

Alert (Alan.getname ());

So we can not let outside people to arbitrarily modify this field, in Java or C # We only need to change this field to Private, everything OK , but Javascript without this keyword, then we need to do this, this is the Blog the meaning of existence is awkward

We can think of what else we can do in C # besides setting up Private . We can set Setter and Getter methods.

Let's change the code above: we call method one:

var person = new Interface ("person", ["SetName", "Setage", "GetName", "getage"]);

var mans = function (name, age) {

This. Setage (age);

This. SetName (name);

}

Man.prototype = {

Setname:function (name) {this. name = name; },

Setage:function (age) {this. Age = age; },

Getname:function () {return this. Name; },

Getage:function () {return this. Age; }

}

var Alan = new Man ("Alan", 25);

Alan.name = "Alice"; tragedy, I became Alice when I was alert.

Alan.setage (Ten);// tragedy, by someone else to give my age so small

Alert (Alan.getname ());

Alan.displayall = function () {return ' Name: ' +this. GetName () + "; Age: ' + this. Getage ()}

Alert (Alan.displayall ());

We found that it looks like a Setter and Getter in C # , but it can still be externally modified. But from the constraints, it looks like the above code lot better Some, through the method to set the initial value. But the problem is still unresolved, let's take a look at one of the following methods: Closures

I need to explain that in Javascript , you develop permissions by using the This keyword ( Public ).

Before we talk about closures, we need to understand the nature of the closures: in Javascript , only methods are scoped, and if the variables declared in the method are not accessible externally, the Private the concept is out.

var person = new Interface ("person", ["SetName", "Setage", "GetName", "getage"]);

var man = function (NewName, newage) {

var name, age;

This. SetName = function (newname) {name = NewName;}

This. Setage = function (newage) {age = NewAge;}

This. GetName = function () {return name;}

This. Getage = function () {return age;}

This. Setage (NewAge);

This. SetName (newname);

}

var Alan = new Man ("Alan", 25);

Alan.name= "Alice"; now that name is private , I can't change it.

Alan.setage (10); tragedy, being someone who gave my age so small

Alert (Alan.getage ());

Now the private function is implemented, we just use Var instead of this . // We refer to publicand accessible Private methods as privileged methods, such as the above This. SetName, this. Setage.

If our public methods do not involve accessing Private fields, then we can put them in the Prototype . // benefits are multiple instances when there is only one copy in memory

Man.prototype.DisplayAll = function () {return ' Name: ' + this. GetName () + "; Age: ' + this. Getage ()}

haha ~ Let's take a look at something slightly more difficult: static variables and methods

We all know that static stuff belongs to class, so let's modify the code below:

var person = new Interface ("person", ["SetName", "Setage", "GetName", "Getage", "GetCount"]);

var man = (function () {

var count = 0;

return function (NewName, newage) {

var name, age;

This. SetName = function (newname) {name = NewName;}

This. Setage = function (newage) {age = NewAge;}

This. GetName = function () {return name;}

This. Getage = function () {return age;}

This. GetCount = function () {return count;}

This. Setage (NewAge);

This. SetName (newname);

count++;

}

})();

Man.prototype.DisplayAll = function () {return ' Name: ' + this. GetName () + "; Age: ' + this. Getage ()}

var Alan1 = new Man ("Alan", 25);

var Alan2 = new Man ("Alan", 25);

Alert ("There is" +alan2.getcount () + "instances of Man");

Whether we go through Alan1 or Alan2 to getcount, the results are all the same 2. here Count is a private static variable.

The use of encapsulation in JavaScript instance tutorials

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.