Home Web Front-end JS Tutorial Discussion on js variable scope and accessibility_javascript skills

Discussion on js variable scope and accessibility_javascript skills

May 16, 2016 pm 07:24 PM

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<10;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<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:

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 "< br>");
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 of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 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

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 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

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles