search
HomeWeb Front-endJS TutorialIntroduction 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:

Copy code The code is as follows:

(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:
Copy code The code is as follows:

(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:
Copy code The code is as follows:

//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:
Copy code The code is as follows:

//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:
Copy code The code is as follows:

//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:
Copy code The code is as follows:

//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:
Copy code The code is as follows:

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.
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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

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 new version

SublimeText3 Linux latest version