Introduction to private/static properties in JavaScript_javascript tips
•Simulate block-level scope
Everyone knows that there is no concept of block-level scope in JavaScript. We can simulate block-level scope by using closures. See the following example:
(function () {
for (var i = 0; i //Do Nothing
}
alert(i); //Output 10
})();
Line 6 can access for The variable i in the loop block, if we slightly modify the above code and place the for loop block in the closure, the situation is different:
(function () {
(function () {
for (var i = 0; i //Do Nothing
}
})();
alert(i); //Error: 'i' is undefined
})();
When accessing changed i in line 8, an error occurred, achieving the block-level scope we wanted.
•Private properties
There is no concept of block-level scope in JavaScript, and there is also no concept of private properties, but there are private variables. What if we want to encapsulate and hide some data? You may have thought that you can implement the private properties of an object by using closures and private variables.
. Instance private attributes
The characteristic of instance private attributes is that each object will contain independent attributes, and there is no sharing between objects. In order to achieve this goal, you can add a private variable in the constructor and then define a public method to access this private variable, just like the setters and getters in other OO languages. The following example implements the private properties of the instance:
//Instance private variable
function MyObject(name) {
//Define private variables
//Note: this.name is not used here. If this.name is used, it becomes a public property
var privateName = name;
//Define private familiarity
var privateFunction = function () {
return "Private Function";
}
//Public method access private familiarity
MyObject.prototype.getName = function () {
return privateName;
}
MyObject.prototype.getFunction = function () {
return privateFunction();
}
}
var moGyy = new MyObject("gyy");
alert (moGyy.getName()); //Output gyy
alert(moGyy.getFunction()); //Output Private Function
var moCyy = new MyObject("cyy");
alert(moCyy. getName()); //Output cyy
alert(moCyy.getFunction()); //Output Private Function
getName of the two objects moGyy and moCyy created in the above example Return different values, and if you want to call private methods, you also need a public interface. In the above example, the reason why the two public functions can access private variables is because the two public functions are closures, and the scope chain of the closure contains the variable object containing the function. Therefore, when searching for variables, the A scope chain allows access to private variables in the containing function. In the above example, public methods are added to the prototype of MyObject to prevent two function instances with the same function from being created every time the object is created.
. Static private attributes
In some cases we may want the data to be shared globally, then static attributes may be used. We still want this attribute to be private, so how to implement static private attributes? ? First of all, this private should be outside the constructor. In order to integrate the variables outside the constructor and the constructor, you can use a closure to include both the private variables and the constructor in its scope. In order to access the internal variables outside the closure Constructor, you can use a global variable to refer to the constructor, as shown in the following code example:
//Static private variables and instance private variables
(function () {
//Define private variables
var staticPrivateValue = "";
//Constructor, constructor Assign the weaving function to a global variable
MyObject = function (name) {
//Define instance variables
this.name = name;
};
//Define two public methods For accessing private variables, add public methods to the prototype again
MyObject.prototype.getPrivateValue = function () {
return staticPrivateValue;
}
MyObject.prototype.setPrivateValue = function (value ) {
staticPrivateValue = value;
}
})();
var mo = new MyObject("jeff-gyy");
mo.setPrivateValue("gyycyy"); / /Set the value of the private attribute
alert(mo.getPrivateValue()); //Output gyycyy
alert(mo.name); //Output jeff-gyy
var mo1 = new MyObject("jeff- cyy");
alert(mo1.getPrivateValue()); //Output gyycyy
alert(mo1.name); //Output jeff-cyy
From the above code See, the value returned by mo1 when calling the getPrivateValue function is the value "gyycyy" set by mo. Why is this? First, we define an anonymous function and call the function immediately. The function contains the private variable staticPrivateValue. Then the two prototype methods defined for MyObject can actually access the private variables in the containing function through the scope chain of the closure, that is, getPrivateValue and setPrivateValue. The scope chain of both functions contains the variable object of the anonymous function. We know that the variable object contained in the scope chain is actually a pointer, so when the two objects created use the public method to house the private variable, they actually access both It is the staticPrivateValue in the variable object of the anonymous function, so it can be shared between variable instances. From the perspective of traditional OO languages, the static properties we implement are not actually static in the true sense, but only realize the sharing of static property instances.
. Module mode and enhanced module mode
Another way to share data globally is singleton. You can use the module mode to implement the singleton mode of the Object type, or you can use the enhanced module mode to implement customization. Singleton pattern of type, as shown in the following example:
//Since Define constructor
var mo = new function () {
//Private variable
var privateValue = "";
//Normal module mode
return {
publicValue: "public ",
//Access private variables
getPrivateValue: function () {
return privateValue;
},
setPrivateValue: function (value) {
privateValue = value;
}
}
}();
mo.setPrivateValue("private value");
alert(mo.getPrivateValue());
alert(mo.publicFunction());
The module mode uses anonymous functions to encapsulate the internal implementation. In the above example, the anonymous function contains the private variable privateValue. The public functions in the returned object access the included function through the scope chain of the closure. Private variables, since the defined anonymous function is called immediately, the variable mo refers to the returned object. The above singleton pattern returns an Object object. You can use the enhanced module pattern to implement a custom type of singleton pattern:
//Enhanced module mode
//Custom constructor
function MyObject(name) {
this.name = name;
} ;
//Custom constructor
var mo = new function () {
//Private variable
var privateValue = "";
//Enhanced module mode
var o = new MyObject("gyycyy");
o.publicValue = "public";
//Access private variables
o.getPrivateValue = function () {
return privateValue;
}
o.setPrivateValue = function (value) {
privateValue = value;
}
return o;
}();
mo.setPrivateValue("private value");
alert(mo.getPrivateValue());
alert(mo.publicFunction());
The above code example implements the singleton mode of MyObject.
The last thing that needs to be mentioned is that there are advantages and disadvantages to using closures. Since the closure scope chain refers to the variable object containing the function, it will occupy additional memory, and the variable search also needs to go through the scope chain, so it will It consumes search time, and the situation is more serious the deeper the closure. In addition, in IE (earlier versions), because the garbage collection mechanism uses reference counting, circular references may occur, leading to memory leaks, as shown in the following example:
function assignHandler(){
var element = document.getElementById("someElement");
element.onclick = function( ){
alert(element.id);
};
}
In the above code, a closure is created as an event of element. The closure refers to the variable object containing the function assingHandler. It is the reference to the variable object that makes the element reference count at least 1, so element will not be recycled, causing memory leaks. You can think of ways to modify it.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software