The summary of this in JS __js

Source: Internet
Author: User
Tags class definition function definition

The this pointer is an important concept in object-oriented programming that represents the currently running object. When you implement a method of an object, you can use the this pointer to obtain a reference to the object itself.

Unlike other object-oriented languages, the This pointer in JavaScript is a dynamic variable, and the this pointer within a method does not always point to the object that defines the method, as has been the case with the apply and call methods of the function in the previous section.

The This keyword in JavaScript usually points to the owner of the current function. In JavaScript, this owner is often called the execution context. The execution context of a function is determined by the current operating environment:

1. Global variables and global functions are attached to global objects (Windows), so it is equivalent to use either the "var" or "This" method to define global variables.

2. The execution context and scope are different. The execution context is determined at run time and may change at any time, while the scope is determined at definition and never changes.

3. If you are currently executing a method of an object, the execution context is the object that this method is attached to.

4. If you are currently creating an object or executing a method of an object, the execution context is the object being created.

5. If a method does not explicitly specify a subordinate object at execution time, the context of this method is a global object.

6. Use call and apply to change the execution context of the object.

Look at the following example:

var v1 = "global variable"; Global variables are attached to objects

THIS.V1 = "global variable with this"; The global variable is defined with the Var v1 and this.v1 two methods equivalent.

function Func1 () {

var v1 = "part variable";

WriteHTML (v1);

WriteHTML (THIS.V1);

}

Func1 (); Part variable

Global variable


Because there are V1 variables with the same name as the global object in the FUNC1, the V1 referenced in FUNC1 is the variable defined in FUNC1. JavaScript also has local variables to hide the properties of global variables. However, FUNC1 does not explicitly specify a subordinate object, so his execution context is a global object, and a global variable is used to refer to the variable.

Let's look at a slightly more complicated example:

function Ftest () {

var v = "v1v1v1";

This.this_v = "This_v";

return function () {

WriteHTML (v);

WriteHTML (This.this_v);

}

}

var a = Ftest ();

var v = "V2v2v2";

WriteHTML (This_v); This_v

A (); V1v1v1

This_v


When Ftest is executed as a function, the context is a global object. Therefore, the variables defined in Ftest are used as global variables. So we use the variable name directly outside the ftest to access the This_v value. However, because the anonymous function returned in ftest is defined within Ftest, the scope of this anonymous function is within Ftest. So when there is a global variable V and a local variable V with the same name, this anonymous function accesses the variable v within the Ftest definition.

Next, take ftest as a class and instantiate it using the New keyword:

function Ftest () {

var v = "v1v1v1";

This.this_v = "This_v";

return function () {

WriteHTML (v);

WriteHTML (This.this_v);

}

}

var a = new Ftest ();

var v = "V2v2v2";

WriteHTML (This_v); Error: This_v not defined

A (); V1v1v1

Undefined


When Ftest is instantiated as an object, the context is the object itself created during the creation of the object. Note that the object created at this time is an instance of Ftest, and a function is returned after the creation completes, which causes the new Ftest () instantiation to return a function instead of the ftest () reference to the object after the instantiation. Therefore, this instantiated object cannot be referenced. When we define this returned function, because the context of this function is not specified with this, the returned function context is the global object, and the scope is internal to the Ftest () function. So when function a () executes, there is no this_v variable defined in the context, resulting in an access error.

Note that the above code:

function Ftest () {

return function () {

}

}


Such a form is not a static encapsulation environment, the static encapsulation environment should be: Execute immediately after a function definition completes, and returns an internal function in the function after the execution completes.

Let's look at one of the following examples to see how scopes and contexts affect variable references.

var v = "global variable";

Function method () {

WriteHTML (v);

WriteHTML (THIS.V);

}

var Class1 = function () {

var v = "Private variable";

THIS.V = "Object variable";



var method2 = method;

This.method2 = method;



var method3 = function () {

WriteHTML (v);

WriteHTML (THIS.V);

}

This.method3 = function () {

WriteHTML (v);

WriteHTML (THIS.V);

}



Method2 (); Global variable

Global variable

THIS.METHOD2 (); Global variable

Object variable

Method3 (); Private variable

Global variable

This.method3 ();//private variable

Object variable

}

var obj = new Class1 ();


Because method is defined globally, the scope of method is determined to be global when defined. So when the METHOD2 is called inside the Class1, its scope is global and the context is a global object. Therefore, the variables that are accessed in the function are global variables.

Similarly THIS.METHOD2 is called, its scope is global, however, because the function uses the This keyword to indicate an object whose context is Class1 when it is defined, a global variable is accessed when the function accesses a variable that has no context qualification, and accesses the corresponding variable in the current context when accessing the context-qualified variable Amount

When Method3 and this.method3 are invoked, a local variable is accessed when accessing a variable that has no context qualification, because the local variable hides the global variable. Has the same context as METHOD2, and accesses the variables in the current up and down text.

Use call and apply to change the execution context, because call and apply are just different parameter types, so the examples are shown using call.

var v = "global variable";

var method = function () {

WriteHTML (THIS.V);

}

var Class2 = function () {

THIS.V = "Object variable in instance of Class2";

This.method = function () {

WriteHTML (THIS.V);

}

}

var Class3 = function () {

THIS.V = "Object variable in instance of CLASS3";

This.method = function () {

WriteHTML (THIS.V);

}

}



var obj2 = new Class2 ();

var obj3 = new Class3 ();



Method (); Global variable

Obj2.method (); object variable in instance of Class2

Obj3.method (); object variable in instance of CLASS3



Method.call (OBJ2); object variable in instance of Class2

Method.call (OBJ3); object variable in instance of CLASS3

Obj2.method.call (OBJ3); object variable in instance of CLASS3

Obj2.method.call (this); Global variable

Obj3.method.call (OBJ2); object variable in instance of Class2

Obj3.method.call (this); Global variable


As you can see, you can bind a method to a specified context by using call or apply. This point in the global context is a global object.

In object-oriented programming languages, we are very familiar with the This keyword. For example, C + +, C # and Java provide this keyword, although at the beginning of learning to feel more difficult, but as long as the understanding, it is very convenient and meaningful to determine. JavaScript also provides this keyword, but it's much more "confusing" than the classic Oo language.

Here's a look at what's confusing about how to use the various this in JavaScript.

1, in the HTML element event properties inline way to use the This keyword:

<div onclick= "
Can use this in the inside

">division element</div>


Our commonly used method is here: Javascirpt:eventhandler (this), such a form. But you can actually write any legitimate JavaScript statements here, and if you're happy to define a class here, you can (but it will be an inner class). The principle here is that the scripting engine generates an Anonymous member method for a div instance object, and the onclick points to this method.

2. Use the This keyword in the event handler function using the DOM method:

<div id= "Elmtdiv" >division element</div>
<script language= "JavaScript" >
var div = document.getElementById (' Elmtdiv ');
Div.attachevent (' onclick ', EventHandler);

function EventHandler ()
{
Use this here
}
</script>


The This keyword in the EventHandler () method indicates that the object is the window object for IE. This is because EventHandler is just an ordinary function, and for attachevent, the script engine has no relationship to its invocation and the Div object itself. You can also look at the caller property of EventHandler, which is equal to NULL. If we want to get a Div object reference in this method, we should use: This.event.srcElement.

3. Use the This keyword in the event handler function in DHTML mode:

<div id= "Elmtdiv" >division element</div>
<script language= "JavaScript" >
var div = document.getElementById (' Elmtdiv ');
div.onclick= function ()
{
Use this here
};
</script>


Here the This keyword indicates a DIV element object instance that uses DHTML in the script to assign a EventHandler method directly to the Div.onclick and adds a member method to the Div object instance. The difference between this and the first approach is that the first approach is to use HTML, which is DHTML, and the script resolution engine no longer generates anonymous methods.

4. Use this keyword in class definition:

function Jsclass ()
{
var myname = ' Jsclass ';
This.m_name = ' Jsclass ';
}

jsclass.prototype.tostring= function ()
{
Alert (myname+ ', ' + this.m_name);
};

var JC = new Jsclass ();
Jc. ToString ();


This is the use of this in the JavaScript impersonation class definition, which is very familiar with the situation in other OO languages. But this requires that member properties and methods must be referenced using the This keyword, and running the program above will be told MyName undefined.

5. Add the This keyword in the prototype method to the script engine internal object:

Function.prototype.GetName = function ()
{
var fnname = this.tostring ();
Fnname= fnname.substr (0, Fnname.indexof ('));
Fnname= Fnname.replace (/^function/, ");
Return Fnname.replace (/(^\s+) | ( \s+$)/g, "");
}
function foo () {}
Alert (foo. GetName ());


This here refers to an instance of the class being added to the prototype, somewhat similar to the class definition in 4, nothing too special.

6, combine 2&4, say a more confusing this keyword uses:

function Jsclass ()
{
This.m_text = ' division element ';
This.m_element = document.createelement (' DIV ');
This.m_Element.innerHTML = This.m_text;

This.m_Element.attachEvent (' onclick ', this. ToString);
}

jsclass.prototype.render= function ()
{
Document.body.appendChild (this.m_element);
}

jsclass.prototype.tostring= function ()
{
alert (This.m_text);
};

var JC = new Jsclass ();
Jc. Render ();
Jc. ToString ();


I'll say it. Results, the page will be displayed after the run: "Divisionelement", OK click on the text "division element", will show: "Undefined."

7, CSS expression expression in the use of this keyword:

<table width= "height=" >
<tr>
<td>
<div style= "width:expression (this.parentElement.width);
Height:expression (this.parentElement.height); " >
Divisionelement</div>
</td>
</tr>
</table>


This here is considered to be the same as in 1, it also refers to the div element object instance itself.

8. Use this keyword in internal functions in functions:

function Outerfoo ()
{
This. name = ' Outer name ';

function Innerfoo ()
{
var name = ' Inner name ';
Alert (name+ ', ' + this.) Name);
}
return innerfoo;
}
Outerfoo () ();


The run results are: "Innername, Outer Name." As we explained in 2, the results here would be more reasonable if they were "innername, undefined". But the correct result is the former, which is determined by the problem of the JavaScript variable scoping, and a detailed reference to "the original JScript keyword ' var ' or the article" text and reply.

Having said so much about this in JavaScript, this most fundamental feature is consistent with the definition in OO language. The reason why there are so many seemingly confusing uses is that the JavaScript language (the content of the interpreter and the language itself) is implemented on an OO (object-based) basis, with all its data types being objects, and a super object such as object. But the language is running (runtime), it does not follow a complete OO feature, so there is a reference to this confusion.

What else in JavaScript is there to use this? That's all I can think of for the time being, welcome to the discussion supplement

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.