Discussion 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:
{
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:
{
var sum = 0;
if(flag = = true)
{
var index;
for(index=0;index<10;index )
{
sum =index;
}
}
document.write("index is :" index "
");
return sum;
}
//document.write("sum is :" sum "
") ;
document.write("result is :" foo(true) "
");
{
var sum = 0;
for(var index=0;index<10;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:
{
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:
{
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");
3. Private methods cannot access the variable (public variable) indicated by this, as follows:
{
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" ));
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:
{
this.name = 이름;
this.age = 나이
this.from =
}
var basicA = new BasicInfo("3zfp",100,"ShenZhen");
basicA.generalInfo = "3zfp 소유 객체입니다";
document.write("basicA의 일반 정보는 " basicA.generalInfo "< br>");
var basicB = new BasicInfo("zfp",100,"ShenZhen");
document.write("basicB의 GeneralInfo는 " basicB.generalInfo "
");
이 코드를 실행하면 다음 결과가 표시됩니다.
basicA의 GeneralInfo는 3zfp 소유 개체입니다.
basicB의 GeneralInfo는 정의되지 않았습니다.
정적 변수는 The입니다. 특정 클래스가 소유한 속성은 클래스 이름 "."을 통해 액세스할 수 있습니다. 명확한 설명은 다음과 같습니다.
{
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 "
"); >위 코드를 실행하면 다음과 같은 결과가 나타납니다.
정의되지 않음
정보가 변경됨
다음 사항에 유의하세요.
1. 클래스 이름 "." 형식 정적 변수
2. 정적 변수는 클래스의 인스턴스 개체에 고유한 속성이 아니라 개체에서 공유됩니다.
3. 개체 이름 "." 정적 변수 이름 .
전역 변수:
전역 변수는 전체 시스템이 작동하는 동안 효과적인 액세스 제어가 가능한 변수입니다. 일반적으로 다음과 같이 js 코드 시작 부분에 정의됩니다. 🎜>
코드 복사
var copyright = "3zfpowned";
var foo = function(fooInfo)
{
_foo = fooInfo
") ;
}
new foo("foo test");
document.write(_foo "
")
코드를 실행하면 다음과 같은 결과가 나타납니다.
3zfp 소유
foo 테스트
그러나 또 다른 주의 사항이 있습니다. 함수는 컴파일 타임 개체이므로 foo 개체가 인스턴스화된 후에만 전역 변수 _foo를 초기화할 수 있습니다. 🎜> new foo();
document.write(_foo "
")
document.write(_foo "
")로 대체됨
new foo( );
시스템에 "_foo가 정의되지 않았습니다"라는 메시지가 표시됩니다.
2. 글로벌 변수와 동일한 이름의 로컬 변수 속성이 정의된 경우
코드 복사
코드는 다음과 같습니다.
")
new foo("foo test").showInfo ();
document.write( copyright "
");
코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
3zfp 소유
foo 테스트
이유는 함수가 컴파일 중에 변수 정의를 완료한다는 것입니다. 즉, foo 내부의 copyright 정의는 컴파일 중에 완료되며, 그 범위는 foo 객체 내에서만 유효하고 외부에서 정의된 전역 변수 copyright과는 아무런 관련이 없습니다.

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

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

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











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
