Home  >  Article  >  Web Front-end  >  Encapsulation, one of JavaScript design patterns

Encapsulation, one of JavaScript design patterns

高洛峰
高洛峰Original
2016-11-25 11:03:011048browse

For those who are familiar with C# and Java, the three major ideas of object-oriented (encapsulation, inheritance, polymorphism) must be understood. Today I want to talk about how to use the feature of encapsulation in Javascript, let’s start!

We will abstract some things in reality into a Class and use the attributes (nouns) of the things as the Properties of the Class and the actions (verbs) of the things as the methods of the Class. In object-oriented languages ​​(C#, etc.) there are some keywords to modify classes or properties (Private, public, protect). These keywords describe the access permissions and will not be explained in detail.

Let’s take a look at the mutable nature of Javascript (we’re still using the example from last time):


var Man = 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 (anonymous method of Javascript) with 2 public fields (this blog will explain in detail, continue reading) ) and 2 public methods, we created an Instance--Alan, but I can dynamically add a DisplayAll method to this Instance. I think any object-oriented language cannot do this. The flexibility of Javascript one.

Let’s now assume a scenario. If many programmers want to use this code, due to the variability of Javascript, programmers can change the value of Name after instantiation, then the initialization action is meaningless:


var Alan = new Man("Alan", 25);       Alan.Name = "Alice"; // Tragedy, when I alerted, I became Alice                                                                                                                                                                                                                    Alan. Let external people modify this field arbitrarily. In Java or C#, we only need to change this field to Private, and everything will be OK. However, Javascript does not have this keyword, so we need to do this. This is this blog The meaning of existence

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

Let’s modify the above code: Let’s call method one:

var Person = new Interface("Person", ["SetName", "SetAge", "GetName", "GetAge"]);   var Man = 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. "Alice"; //Tragedy, I became Alice when I alerted Alan.SetAge(10);//Tragedy, someone made me so young alert(Alan.GetName()); Alan.DisplayAll = function () { return "Name: "+this.GetName() + "; Age: " + this.GetAge() } alert(Alan.DisplayAll());


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

//I need to explain that permissions (Public) are developed through the This keyword in Javascript.

Before talking about closures, we need to understand the essence of closures: In Javascript, only methods have scope. If the variables declared in the method are not accessible from the outside, then the concept of Private comes 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 the name is private, I cannot modify it Alan .SetAge(10); //Tragedy, someone else gave me such a young age alert(Alan.GetAge());


Now the private function is implemented, we just use Var to replace This. //We call methods that are public and can access Private called privileged methods, such as this.SetName, this.SetAge above.

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


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


Haha~ Let’s take a look at something a little more difficult: static variables and methods

We all know that static things belong to classes (Class), let’s modify the above code:


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 are "+Alan2.GetCount()+" instances of Man" );


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