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

Discussion on js variable scope and accessibility_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:24:00968browse

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