search
HomeWeb Front-endJS TutorialDiscussion on js variable scope and accessibility_javascript skills

Every language has the concept of a variable, which is an element used to store information. For example, the following function:

Copy code The code is as follows:
function Student(name,age, from)
{
this.name = name;
this.age = age;
this.from = from;
this.ToString = function()
{
return "my information is name: " this.name ",age : " this.age ", from :" this.from;
}
}

The Student class has three variables, namely Name, age, and from, these three variables constitute the information describing an object. Of course, there is also a method to return Student information.
But, if we define a variable, it will always exist and may be accessed and used anywhere until it is destroyed? If you think about it carefully, the above requirements are quite excessive, because some variables will no longer be used after a certain function is implemented, but if this variable still exists, it will occupy system resources. As the saying goes: "Standing in the pit Don’t pull #$%”.
So we have a topic to discuss about the timely and on-demand destruction of variables.
Okay, let’s get to the point. As far as I’ve come across, js supports the following types of variables: local variables, class variables, private variables, instance variables, static variables and global variables. Next we will discuss and study them one by one.

Local variables:

Local variables generally refer to variables that are valid within the scope of {}, that is, variables that are valid within the statement block, such as:

Copy code The code is as follows:
function foo(flag)
{
var sum = 0;
if(flag = = true)
{
var index;
for(index=0;index {
sum =index;
}
}
document.write("index is :" index "
");
return sum;
}
//document.write("sum is :" sum "
") ;
document.write("result is :" foo(true) "
");
The output results after execution of this code are: "index is :undefined" and "result is :0" , we can see that the value of the index variable we want to output is undefined, that is, undefined. Therefore, we can find that the index variable is destroyed after the if statement block ends. What about the "sum" variable? This variable is destroyed after the foo() function section is executed. If you remove the statement I commented and execute it again, you will find that the system will report an error. It is worth noting that if I change the foo() function above to the following:

Copy the code The code is as follows:
function foo(flag)
{
var sum = 0;
for(var index=0;index {
sum =index;
}
document.write("index is :" index "
");
return sum;
}

You will be able to see that the index value ("index is :10") can be output. This is the difference between js and other languages. Because index is defined outside the {} of the for loop, its scope is foo( ) function is destroyed after use.

Class variable:
Class variable is actually an attribute or field or a method of the class. This variable is automatically destroyed after an instance object of the class is destroyed, such as the Student we mentioned at the beginning kind. We won’t discuss this much, you can try it yourself.

Private variable:
Private variable is an attribute used internally by a class and cannot be called externally. Its definition is declared using var. Note that if declared without var, the variable will be a global variable (we will discuss it below), such as:

Copy code The code is as follows:
function Student(name,age,from)
{

this.name = FormatIt(name);
this.age = age;
this.from = from;
var origName = name;
var FormatIt = function(name)
{
return name.substr(0,5);
}
this .ToString = function()
{
return "my information is name: " origName ",age : " this.age ", from :" this.from;
}
}

Here, we define two private variables, one origName and FormatIt() respectively (according to the object-oriented interpretation, they should be called by the attributes of the class).
We also call the method in this case a variable, because the variable in this case is a function type variable, and function also belongs to the inheritance class of the Object class. In this case, if we define var zfp = new Student("3zfp",100,"ShenZhen"). But these two variables cannot be accessed through zfp.origName and zfp.FormatIt().

Note the following points:

1. Private variables cannot be indicated by this.
2. The call to a variable of private method type must be after the method is declared. For example, we transform the Student class as follows:

Copy the code The code is as follows:
function Student(name ,age,from)
{
var origName = name;
this.name = FormatName(name);
this.age = age;
this.from = from;
var FormatName = function(name)
{
return name ".china";
}
this.ToString = function()
{
return "my information is name: " origName ",age : " this.age ", from :" this.from;
}
}
var zfp = new Student("3zfp",100,"ShenZhen");
code After execution, an "object not found" error will be reported. This means that FormatName() is not defined.

3. Private methods cannot access the variable (public variable) indicated by this, as follows:


Copy code The code is as follows:
function Student(basicinfo)
{
this.basicInfo = basicinfo;

var FormatInfo = function()
{
this.basicInfo.name = this.basicInfo.name ".china";
}
FormatInfo();
}
function BasicInfo(name,age,from)
{
this.name = name;
this.age = age;
this.from = from;
}
var zfp = new Student(new BasicInfo("3zfp",100,"ShenZhen" ));
After executing the code, the system will prompt the error "this.basicInfo is empty or not an object".
The basic conclusion is that private methods can only access private properties. Private properties can be accessed anywhere in the class after being declared and assigned.

Instance variables:
Instance variables are where an instance object belongs. Owned variables. For example:
Copy code The code is as follows:
함수 BasicInfo(이름,나이,from)
{
this.name = 이름;
this.age = 나이
this.from =
}
var basicA = new BasicInfo("3zfp",100,"ShenZhen");
basicA.generalInfo = "3zfp 소유 객체입니다";
document.write("basicA의 일반 정보는 " basicA.generalInfo "");
var basicB = new BasicInfo("zfp",100,"ShenZhen");
document.write("basicB의 GeneralInfo는 " basicB.generalInfo "
");
이 코드를 실행하면 다음 결과가 표시됩니다.
basicA의 GeneralInfo는 3zfp 소유 개체입니다.
basicB의 GeneralInfo는 정의되지 않았습니다.
정적 변수:

정적 변수는 The입니다. 특정 클래스가 소유한 속성은 클래스 이름 "."을 통해 액세스할 수 있습니다. 명확한 설명은 다음과 같습니다.

코드 복사 코드는 다음과 같습니다.
function BasicInfo(이름, 나이,from)
{
this.name = 이름;
this.age = 나이
this.from =
}
BasicInfo.generalInfo; = "3zfp 소유 객체입니다";
var basic = new BasicInfo("zfp",100,"ShenZhen")
document.write(basic.generalInfo "
"); .write(BasicInfo.generalInfo "
");
BasicInfo.generalInfo = "정보가 변경되었습니다."
document.write(BasicInfo.generalInfo "
"); >위 코드를 실행하면 다음과 같은 결과가 나타납니다.
정의되지 않음
is 3zfp 소유 개체
정보가 변경됨

다음 사항에 유의하세요.
1. 클래스 이름 "." 형식 정적 변수
2. 정적 변수는 클래스의 인스턴스 개체에 고유한 속성이 아니라 개체에서 공유됩니다.
3. 개체 이름 "." 정적 변수 이름 .

전역 변수:
전역 변수는 전체 시스템이 작동하는 동안 효과적인 액세스 제어가 가능한 변수입니다. 일반적으로 다음과 같이 js 코드 시작 부분에 정의됩니다. 🎜>

코드 복사

코드는 다음과 같습니다.var copyright = "3zfpowned"; var foo =function() { window.alert(copyright ); }
다음 사항에 유의하세요.
1. 변수가 var 없이 선언되면 전역 변수로 간주됩니다. 예:
var copyright = "3zfpowned";
var foo = function(fooInfo)
{
_foo = fooInfo
document.write(copyright "
") ;
}
new foo("foo test");
document.write(_foo "
")
코드를 실행하면 다음과 같은 결과가 나타납니다.
3zfp 소유
foo 테스트
그러나 또 다른 주의 사항이 있습니다. 함수는 컴파일 타임 개체이므로 foo 개체가 인스턴스화된 후에만 전역 변수 _foo를 초기화할 수 있습니다. 🎜> new foo();
document.write(_foo "
")

document.write(_foo "
")로 대체됨
new foo( );
시스템에 "_foo가 정의되지 않았습니다"라는 메시지가 표시됩니다.
2. 글로벌 변수와 동일한 이름의 로컬 변수 속성이 정의된 경우




코드 복사


코드는 다음과 같습니다.
var copyright = "3zfpowned"; var foo = function(fooInfo) { var copyright = fooInfo; 🎜> this.showInfo = function() { document.write(copyright "
")
}
}
new foo("foo test").showInfo ();
document.write( copyright "
");
코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
3zfp 소유
foo 테스트

이유는 함수가 컴파일 중에 변수 정의를 완료한다는 것입니다. 즉, foo 내부의 copyright 정의는 컴파일 중에 완료되며, 그 범위는 foo 객체 내에서만 유효하고 외부에서 정의된 전역 변수 copyright과는 아무런 관련이 없습니다.
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

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

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

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 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

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

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

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

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

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

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

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

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

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

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool