This keyword in the C++,java is provided in this keyword, in the beginning of learning to find it difficult, but as long as the understanding of the use of more convenient, the following through this article to give you a detailed understanding of this keyword in JS.
About this, is a lot of front-end interview must test the topic, sometimes on the internet to see these topics, I tried a bit, the amount, really wrong! In actual development, you will also encounter this problem (although some class libraries will handle it for us), for example, when using some frameworks, such as: knockout, sometimes you don't understand why you don't use this directly, but you want to pass this as a parameter.
Next you talk about my understanding of it, also as a note, easy to see later. There are some wrong places, please point out the criticism.
1. Unlike c#,this must point to the current object.
The this point of JS is indeterminate, that is to say, it can be changed dynamically. Call/apply is the function that is used to change this point, so that the design can make the code more flexible and more reusable.
2. This is generally the owner of the function.
This is important! This is important! This is important!
This is also a common face test, the following code:
<script type= "Text/javascript" >
var number = 1;
var obj = {
number:2,
shownumber:function () {
this.number = 3;
(function () {
console.log (this.number);
})();
Console.log (this.number);
}
};
Obj.shownumber ();
</script>
Because the owner of the Shownumber method is obj, so this.number=3; This point is the attribute number of obj.
Similarly, the second Console.log print is also a property number.
Why the 2nd says this is generally the owner of the function because there is a special case. The function itself is a special case, in the function itself, this point is: window. So the first Console.log print is the window's attribute number.
So add a little more:
3. In the function from execution, this points to the Window object.
Extension, about this, there's another place that's a bit blurry. In DOM events, there are usually 3 scenarios:
As follows:
1. Use the Label property to register the event, at which point this is the Window object.
<input id= "test" type= "button" value= "buttons" onclick= "Test ()"/>
function test () {alert (this)}
2. For 1, to let this point to input, you can pass this as a parameter.
3. Use AddEventListener, etc. registration. This also points to input.
document.getElementById ("Test"). AddEventListener ("click", test);
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 all of this in JavaScript?
1, in the HTML element event properties inline way to use the This keyword:
This
">division element
//can be used in the inside to use this
" >division element
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:
Division element
var div = document.getElementById (' Elmtdiv ');
Div.attachevent (' onclick ', EventHandler);
function EventHandler ()
{
//Use this
}
//-->
Division element
var div = document.getElementById (' Elmtdiv ');
Div.attachevent (' onclick ', EventHandler);
function EventHandler ()
{
//Use this in this
}
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:
Division element
Lt;mce:script language= "JavaScript" >
var div = document.getElementById (' Elmtdiv ');
Div.onclick = function ()
{
//This is used in this
};
/-->
Division element
var div = document.getElementById (' Elmtdiv ');
Div.onclick = function ()
{
//This is used in this
};
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 ();
function Jsclass ()
{
var myname = ' Jsclass ';
This.m_name = ' Jsclass ';
}
JSClass.prototype.ToString = function ()
{
alert (myname + ', ' + this.m_name);
};
var JC = new Jsclass ();
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 ());
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 () {}
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:
view plaincopy to Clipboardprint? 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 ();
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: "Division Element", and then click on the text "division element", will show: "Undefined."
7, CSS expression expression in the use of this keyword:
Height:expression (this.parentElement.height); " >
Division Element
Height:expression (this.parentElement.height); >
Division Element
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:
View Plaincopy to Clipboardprint?
function Outerfoo ()
{this
. name = ' Outer name ';
function Innerfoo ()
{
var name = ' Inner name ';
Alert (Name + ', ' + this.) Name);
return innerfoo;
}
Outerfoo () ();
function Outerfoo ()
{this
. name = ' Outer name ';
function Innerfoo ()
{
var name = ' Inner name ';
Alert (Name + ', ' + this.) Name);
return innerfoo;
}
The run result is: "Inner name, Outer name." As we explained in 2, here's the result if "Inner Name, undefined" seems more reasonable? 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.
To sum up, this usage in JavaScript has the following 3 kinds (detailed usage parameter original text):
1. Use the This keyword inline in an HTML element event property or in a expression expression in CSS--1, 7 for the original
2. Use the This keyword in the event handler function--2, 3 corresponding to the original
which can be divided into two ways
(1) Dom Way-The result of this is this point to the Window object
(2) DHTML Way--the result of this is this point to the DIV element object instance
3. Use the This keyword in the class definition and use it in its internal function or member function (mainly prototype)-4, 5, 8 of the corresponding original text
It should be explained that the function is also an object, so you need to differentiate between the variable definition and the member variable definition, as follows:
View Plaincopy to Clipboardprint?
var variableName; Variable definition
/scope: function definition scope
//Use method: Direct use of variablename
this.varname; Member variable definition
/scope: Function object definition scope and its member function
//use method: This.varname
var variableName; Variable definition
/scope: function definition scope
//Use method: Direct use of variablename
this.varname; Member variable definition
/scope: Function object definition scope and its member function
//use method: This.varname
The first of the three types of this method is easy to understand, and the procedure mentioned in the 6th is tested and improved as follows to illustrate the following two ways of using:
View Plaincopy to Clipboardprint? function Jsclass () {var vartext = "Func variable!"; The ordinary variable this.m_text = ' func member! ' in the function; Function class member Variable this.m_element = document.createelement (' DIV '); Member variable, create a div object this.m_Element.innerHTML = vartext; Use the normal variable of the function this.m_Element.attachEvent (' onclick ', this. ToString);
This.newelement = document.createelement (' DIV ') to the event attached to this object;
This.newElement.innerHTML = "new element"; This.newElement.m_Text = "new element text!"; Build a member This.newElement.onclick = function () {alert (This.m_text) for the created object;
Points to a Div object's member}; } JSClass.prototype.Render = function () {document.body.appendChild (this.m_element);
Hang the Div object on the window Document.body.appendChild (this.newelement); } JSClass.prototype.ToString = function () {ALERT (This.m_text);
Point to Window Object};
function Initialize () {var JC = new Jsclass (); Jc.
Render (); Jc. ToString ();
This here points to an instance of the Jsclass class, which has M_text member}//--> initialize (); --> function Jsclass () {var vartext = "Func variable!"; The ordinary variable this.m_text = ' func member! ' in the function; Function class member Variable this.m_element = document.createelement (' DIV '); Member variable, create a div object this.m_Element.innerHTML = vartext; Use the normal variable of the function this.m_Element.attachEvent (' onclick ', this. ToString);
This.newelement = document.createelement (' DIV ') to the event attached to this object;
This.newElement.innerHTML = "new element"; This.newElement.m_Text = "new element text!"; Build a member This.newElement.onclick = function () {alert (This.m_text) for the created object;
Points to a Div object's member}; } JSClass.prototype.Render = function () {document.body.appendChild (this.m_element); To hang a Div object on a window
Document.body.appendChild (this.newelement); } JSClass.prototype.ToString = function () {alert (this.m_text);
Point to Window Object};
function Initialize () {var JC = new Jsclass (); Jc.
Render (); Jc. ToString ();
This here points to an instance of the Jsclass class, which has M_text member}//--> initialize (); -->
The above code execution results are:
When the page loads, the pop-up dialog box, output func member!
Show on page
Func variable!
New element
When you click Func variable, the pop-up dialog box displays undefined
--because then the this pointer in the ToString function points to window
When you click New element, the pop-up dialog box displays the new element text!
-because then the this pointer in the ToString function points to the DIV element, which already defines the M_text member (This.newElement.m_Text = "new element text!" )