Scopes and keywords in javascript this

Source: Internet
Author: User
Tags closure

I. Scope

When code executes in an environment, a scope chain consisting of variable objects is created to ensure orderly access to all variables and functions that have access to the execution environment. Identifier parsing is a search identifier process along the scope chain, starting at the front of the scope chain and then backtracking backwards until the identifier is found.

-----------------------------------------------------------------------------------------------

1. Common Basic Scopes

var color= ' Red ';

function Firstcolor () {

var acolor= "Blue";

function Bcolor () {

var Xxcolor=acolor;

Acolor=color;

}

Bcolor ()

}

Firstcolor ();

There are three execution environments: Global environment, Firstcolor and bcolor two local environments, variables in local environments can only be accessed in the current environment, but access to a higher level of environment, FIRSTCOLOR environment and global environment can not access Xxcolor But Bcolor can access the global and firstcolor environments.

-------------------------------------------------------------------------------------------------

2. Misunderstandings difficult to understand

var name= "D";

function aa () {

alert (name);

var name= ' CC ';

alert (name);

}

AA ();//underfind,cc;

Analysis: Functions in the internal scope of the first search for the variable name, because the function execution is in order, the first alert when name is not found in the AA function will be looked down, under the definition of name, the global variable name= "D" But when the first alert is executed, name simply passes the variable definition to name in the first alert, and the value of the variable definition does not pass through. The equivalent of declaring a variable name before the first alert, but the value is undefined. So the first alert came out of Underfind. If replaced into

var name= "D";

function aa () {

alert (name);

}

AA ();//d

The function's internal scope could not find the name definition at function execution, so it went to the nearest scope to find the definition of the variable, at which point the external variable passed the variable and the value to alert so the result would be "D".

------------------------------------------------------------------------------------------------

3. Changing scopes

Use the call or Apply method (for example, call):

var name= "AAA";

var object={name: "BBB"};

function Sayname () {

Alert (this.name)

}

Sayname ();//aaa

Sayname.call (object);//bbb

Instantiate a function or object with new:

function ChangeName (name) {
This.name=name;

This.sayname=function () {

alert (this.name);

}
}

If the direct changename ("DD"). Sayname () is an error, because Sayname is present at Windows Global.

var newname=new changename ("xx");

Newname.sayname ()//xx

Instantiating an object (a function is also an object) means that the constructor (ChangeName) scope is assigned to the new object (NewName), at which point this points to the new object and then creates a property for the new object within the constructor, and finally returns the NewName new object.

====================================================================

two. keyword this

The book says, "This object is bound at run time based on the execution environment of a function." That is to say, this is pure. If not invoked, it represents only one symbol, not any object, that produces an internal object when called, and the object's pointer points to that instance (the context). In global functions, this equals window, and when a function is called as a method of an object, this equals that object, and the execution environment of the anonymous function is global, so this usually points to window (apply can change the environment)

----------------------------------------------------------------------------------------------

var age= "12";

var obj={

Age: "22",

Changeage:function () {
return function () {

return this.age;

}
}

}

Alert (Obj.changeage () ())//12

When each function is invoked, its active object gets a special variable this, and the internal function searches for the variable only until its active object is searched, so it can never directly access this in the external function. In this code, an anonymous function is used as a closure to invoke the age attribute of the Obj object, while the anonymous function activity object is only within the changeage, so this points to window, so the output value is 12.

There are two ways to change this scope:

Use apply to change the environment:

var age= "12";

var obj={

Age: "22",

Changeage:function () {
return function () {

return this.age;

}.apply (This)
}

}

Alert (Obj.changeage ())//22

This time apply apply to the anonymous function and point the Anonymous function object to obj. The this.age at this point is 22, which modifies the scope of an anonymous function by using apply, which is equivalent to being called once, so the anonymous function is executed, so the anonymous function is not executed at the time of the call.

2. Save the external this as a closed package accessible variable:

var age= "12";

var obj={

Age: "22",

Changeage:function () {

var that=this;

return function () {

return that.age;

};
}

}

Alert (Obj.changeage () ())//22

This way, before you define an anonymous function, assigning the This object to a variable named that, and after the closure is defined, the closure can also access the variable (because it is a variable that we deliberately declare in the containing function) even after the function returns, that still references obj. So the call to Obj.changeage () () also returns "22"

-----------------------------------------------------------------------------------------

The other place is the object-oriented and inheritance process of JS. This is also referred to in the scope where the scope is not separable;

var obj=function () {

This.name= "a";

This.sayname=function () {

Alert (this.name)

}

}

A direct call to Obj.sayname () will cause the error to be sayname because the name and Sayname () before the instantiation of this pointer point to window.

If you call Window.sayname () directly, you will output the results we expect. It is instantiated and then called, var a=new obj (); A.sayname () is fine.

Obj.prototype.changename=function () {this.name= "second"};

This uses a prototype to access a new method and change the name in the prototype;

Call Method:

var a=new obj ();

A.changename ();

Alert (A.name)//"second";

Delete A.name;

Alert (A.name)//"a"

After instantiating the original constructor here, calling ChangeName is equivalent to masking the original property of name in the instance function object, which only exists in the instance, and the name sign in the prototype does not change. So after delete, A.name still finds the name attribute defined in the constructor along the prototype chain.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.