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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

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

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 Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version