This article is divided into two parts. The first part talks about basic patterns: the complete exposure method, the underline marking method and the use of closures; the second part talks about advanced patterns, how to implement static methods and attributes, and there are other knowledge points in constants.
Encapsulation is a very basic and useful feature of object-oriented language. Although JavaScript can also be called an object-oriented language, its support for encapsulation is not very good. Unlike other languages, it can be implemented as long as private and protected. But this does not mean that there is no way. Let me introduce how to implement encapsulation in javascript.
1. Basic patterns,It mainly includes three methods: complete exposure method, underscore marking method and use of closures. (Closing is a very important and difficult concept. Interested friends can go online to find information, and I also reprinted other people's articles in my blog).
Here we take the book class as an example, and we need to create and initialize the book class.
// Book(isbn, title, author)
var theHobbit = new Book('0-395-07122-4', 'The Hobbit', 'J. R. R. Tolkien');
(); // Outputs the data by creating and populating an HTML element.
1. Complete exposure method:
Create book classes in the most traditional way.
var Book = function(isbn, title, author) {
if(!(isbn)) throw new Error('Book: Invalid ISBN.');
= isbn;
//The function of || in the code is that if the title has no value, 'No title specified' will be assigned to . This method is very useful and can be used in your own code.
= title || 'No title specified';
= author || 'No author specified';
}
= {
//Verify the isbn function
checkIsbn: function(isbn) {
...
},
//Get isbn
getIsbn: function() {
return ;
},
//Set isbn
setIsbn: function(isbn) {
if(!(isbn)) throw new Error('Book: Invalid ISBN.');
= isbn;
},
//Get title
getTitle: function() {
return ;
},
//Set title
setTitle: function(title) {
= title || 'No title specified';
},
//Get the author
getAuthor: function() {
return ;
},
//Set the author
setAuthor: function(author) {
= author || 'No author specified';
},
//Display function
display: function() {
...
}
};
There are a lot of codes, I will briefly explain them here. Create classes in javascript and c#, java is a bit different. C#, java will wrap all methods and attributes in a class file, for example
public class book()
{
private string isbn;
public string ISBN
{
set
{
=value;
}
get
{
return ;
}
}
...
private bool CheckIsbn(string isdn)
{
......
}
......
public void Display()
{
......
}
}
JavaScript can also be used in this way, but it is recommended to use the one I used above to define attributes to class-defined functions (or constructors) and methods to prototype objects. This method has better performance. As for the reasons, you can google.
The function that the above js code wants to implement is to define a book class, which includes three private variables (or attributes) isbn, title, author, a private method checkIsbn, several public methods getIsdn, setIsdn, ...display. The idea is good, but the reality is cruel. In fact, those private attributes or methods are not private at all. For example, = '978-0261103283'; You can assign a value to isbn in this way, without errors and absolutely successful. The reason is that JavaScript does not have a private method to implement the privatization of specific objects. In addition, this implementation method will also cause confusion when used. What attributes and methods do the creators of the class want to expose? The first improvement method is introduced below, the underline marking method.
2. Underline marking method:
var Book = function(isbn, title, author) {
// Constructor code.
(isbn);
(title);
(author);
}
= {
//Verify the isbn function
_checkIsbn: function(isbn) {
...
},
//Get isbn
getIsbn: function() {
return this._isbn;
},
//Set isbn
setIsbn: function(isbn) {
if(!this._checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
this._isbn = isbn;
},
...
//Display function
display: function() {
...
}
};
In fact, it is underlined before all properties or methods that want to implement private, and there is no other operation. This method does not realize real privatization, theHobbit._isbn = '978-0261103283'; This operation is still successful. The biggest significance of this method is to tell the user of the class what objects the author wants to expose in his original intention and what they do not want to expose. However, the author cannot control whether the user follows the author's ideas.
So is there a way to achieve real privatization? The answer is, it is to use closures.
3. Use closures:
The reason why JavaScript can implement real encapsulation is that it is inseparable from its unique function scope, which supports internal functions, and closures. You can collect relevant knowledge online to deepen your understanding.
The first thing to talk about below is the function scope. If a variable is defined inside a function in javascript, then there is no way to access it outside the function. In fact, implementing private attributes or methods in javascript is to use this special attribute. example:
function foo() {
var a = 10;
function bar() {
a *= 2;
}
bar();
return a;
}
In the above example, the function foo defines the variable a and method bar internally. A and bar cannot be accessed outside foo, but because a and bar are both defined inside foo, bar can access a. So is there a way to access the bar outside foo? The answer is, it is to use closures.
function foo() {
var a = 10;
function bar() {
a *= 2;
return a;
}
return bar;
}
var baz = foo(); // baz is now a reference to function bar.
baz(); // returns 20.
baz(); // returns 40.
baz(); // returns 80.
var blat = foo(); // blat is another reference to bar.
blat(); // returns 20, because a new copy of a is being used.
This is what the JavaScript function mentioned earlier supports internal functions. The internal function bar can access the private variable a, and the function foo throws the internal function bar to baz, and baz can access the internal variable a, which implements the closure. Everyone will understand at a glance, which actually implements private variables and methods. Going back to our previous book example, the implementation is as follows:
var Book = function(newIsbn, newTitle, newAuthor) {
// implements Publication
// Private attributes.
var isbn, title, author;
// Private method.
function checkIsbn(isbn) {
...
}
// Privileged methods.
= function() {
return isbn;
};
= function(newIsbn) {
if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
isbn = newIsbn;
};
= function() {
return title;
};
= function(newTitle) {
title = newTitle || 'No title specified';
};
= function() {
return author;
};
= function(newAuthor) {
author = newAuthor || 'No author specified';
};
// Constructor code.
(newIsbn);
(newTitle);
(newAuthor);
};
// Public, non-privileged methods.
= {
display: function() {
...
}
};
The above code implements the privatization of isbn, title, author and checkIsbn, and the external decision cannot be accessed directly. If you need to access isbn, title, author, you can only use object-level methods getTitle, setTitle.... For example, if you want to assign a value to isbn, you can only use = '978-0261103283';, if you still use theHobbit._isbn = '978-0261103283';, I'm sorry for reporting an error.
Okay, that’s all for today’s content, I hope it will be helpful to everyone.
Author: Next stop forever
Encapsulation is a very basic and useful feature of object-oriented language. Although JavaScript can also be called an object-oriented language, its support for encapsulation is not very good. Unlike other languages, it can be implemented as long as private and protected. But this does not mean that there is no way. Let me introduce how to implement encapsulation in javascript.
1. Basic patterns,It mainly includes three methods: complete exposure method, underscore marking method and use of closures. (Closing is a very important and difficult concept. Interested friends can go online to find information, and I also reprinted other people's articles in my blog).
Here we take the book class as an example, and we need to create and initialize the book class.
Copy the codeThe code is as follows:
// Book(isbn, title, author)
var theHobbit = new Book('0-395-07122-4', 'The Hobbit', 'J. R. R. Tolkien');
(); // Outputs the data by creating and populating an HTML element.
1. Complete exposure method:
Create book classes in the most traditional way.
Copy the codeThe code is as follows:
var Book = function(isbn, title, author) {
if(!(isbn)) throw new Error('Book: Invalid ISBN.');
= isbn;
//The function of || in the code is that if the title has no value, 'No title specified' will be assigned to . This method is very useful and can be used in your own code.
= title || 'No title specified';
= author || 'No author specified';
}
= {
//Verify the isbn function
checkIsbn: function(isbn) {
...
},
//Get isbn
getIsbn: function() {
return ;
},
//Set isbn
setIsbn: function(isbn) {
if(!(isbn)) throw new Error('Book: Invalid ISBN.');
= isbn;
},
//Get title
getTitle: function() {
return ;
},
//Set title
setTitle: function(title) {
= title || 'No title specified';
},
//Get the author
getAuthor: function() {
return ;
},
//Set the author
setAuthor: function(author) {
= author || 'No author specified';
},
//Display function
display: function() {
...
}
};
There are a lot of codes, I will briefly explain them here. Create classes in javascript and c#, java is a bit different. C#, java will wrap all methods and attributes in a class file, for example
Copy the codeThe code is as follows:
public class book()
{
private string isbn;
public string ISBN
{
set
{
=value;
}
get
{
return ;
}
}
...
private bool CheckIsbn(string isdn)
{
......
}
......
public void Display()
{
......
}
}
JavaScript can also be used in this way, but it is recommended to use the one I used above to define attributes to class-defined functions (or constructors) and methods to prototype objects. This method has better performance. As for the reasons, you can google.
The function that the above js code wants to implement is to define a book class, which includes three private variables (or attributes) isbn, title, author, a private method checkIsbn, several public methods getIsdn, setIsdn, ...display. The idea is good, but the reality is cruel. In fact, those private attributes or methods are not private at all. For example, = '978-0261103283'; You can assign a value to isbn in this way, without errors and absolutely successful. The reason is that JavaScript does not have a private method to implement the privatization of specific objects. In addition, this implementation method will also cause confusion when used. What attributes and methods do the creators of the class want to expose? The first improvement method is introduced below, the underline marking method.
2. Underline marking method:
Copy the codeThe code is as follows:
var Book = function(isbn, title, author) {
// Constructor code.
(isbn);
(title);
(author);
}
= {
//Verify the isbn function
_checkIsbn: function(isbn) {
...
},
//Get isbn
getIsbn: function() {
return this._isbn;
},
//Set isbn
setIsbn: function(isbn) {
if(!this._checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
this._isbn = isbn;
},
...
//Display function
display: function() {
...
}
};
In fact, it is underlined before all properties or methods that want to implement private, and there is no other operation. This method does not realize real privatization, theHobbit._isbn = '978-0261103283'; This operation is still successful. The biggest significance of this method is to tell the user of the class what objects the author wants to expose in his original intention and what they do not want to expose. However, the author cannot control whether the user follows the author's ideas.
So is there a way to achieve real privatization? The answer is, it is to use closures.
3. Use closures:
The reason why JavaScript can implement real encapsulation is that it is inseparable from its unique function scope, which supports internal functions, and closures. You can collect relevant knowledge online to deepen your understanding.
The first thing to talk about below is the function scope. If a variable is defined inside a function in javascript, then there is no way to access it outside the function. In fact, implementing private attributes or methods in javascript is to use this special attribute. example:
Copy the codeThe code is as follows:
function foo() {
var a = 10;
function bar() {
a *= 2;
}
bar();
return a;
}
In the above example, the function foo defines the variable a and method bar internally. A and bar cannot be accessed outside foo, but because a and bar are both defined inside foo, bar can access a. So is there a way to access the bar outside foo? The answer is, it is to use closures.
Copy the codeThe code is as follows:
function foo() {
var a = 10;
function bar() {
a *= 2;
return a;
}
return bar;
}
var baz = foo(); // baz is now a reference to function bar.
baz(); // returns 20.
baz(); // returns 40.
baz(); // returns 80.
var blat = foo(); // blat is another reference to bar.
blat(); // returns 20, because a new copy of a is being used.
This is what the JavaScript function mentioned earlier supports internal functions. The internal function bar can access the private variable a, and the function foo throws the internal function bar to baz, and baz can access the internal variable a, which implements the closure. Everyone will understand at a glance, which actually implements private variables and methods. Going back to our previous book example, the implementation is as follows:
Copy the codeThe code is as follows:
var Book = function(newIsbn, newTitle, newAuthor) {
// implements Publication
// Private attributes.
var isbn, title, author;
// Private method.
function checkIsbn(isbn) {
...
}
// Privileged methods.
= function() {
return isbn;
};
= function(newIsbn) {
if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
isbn = newIsbn;
};
= function() {
return title;
};
= function(newTitle) {
title = newTitle || 'No title specified';
};
= function() {
return author;
};
= function(newAuthor) {
author = newAuthor || 'No author specified';
};
// Constructor code.
(newIsbn);
(newTitle);
(newAuthor);
};
// Public, non-privileged methods.
= {
display: function() {
...
}
};
The above code implements the privatization of isbn, title, author and checkIsbn, and the external decision cannot be accessed directly. If you need to access isbn, title, author, you can only use object-level methods getTitle, setTitle.... For example, if you want to assign a value to isbn, you can only use = '978-0261103283';, if you still use theHobbit._isbn = '978-0261103283';, I'm sorry for reporting an error.
Okay, that’s all for today’s content, I hope it will be helpful to everyone.
Author: Next stop forever