


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 < 10; 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 < 10; 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.
<1>. 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.
<2>. 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.
<3>. 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.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona
