The example in this article analyzes the use of this in JavaScript. Share to everyone for your reference, specific as follows:
One. " This "axiom
The This keyword always points to the owner of the function (method);
function fn1 () {
this
};
FN1 (); This=>window
odiv.onclick=fn1//this=>odiv
odiv.onclick=function () {This
//this=>odiv
fn1 ();//this=>window
}
<div onclick= "this.fn1 ();" ></div>//The scripting of these rows is now very rare.
This here points to the this point in div,fn1 () to the window
var it=
{
info:["Tencent", "Sohu", "Sina", "Baidu"],
getinfo:function ()
{
alert (This.info.join (","));
}
};
It.getinfo ();
Output: Tencent, Sohu, Sina, Baidu
Two. The "This" problem when a function is assigned to a variable
var it=
{
info:["Tencent", "Sohu", "Sina", "Baidu"],
getinfo:function ()
{
alert (This.info.join (","));
var data=it.getinfo;
Data ();
Output: Error, TypeError:this.info is undefined
Code is equivalent to
var data=function () {
alert (This.info.join (","));
Data ();
Here's this point to window, where the data is assigned, if it is Var data=it.getinfo (); That's the call, the result is Tencent, Sohu, Sina, Baidu. If Alert (This.it.info.join (",")), the result is Tencent, Sohu, Sina, Baidu.
var info=["QQ", "Sohu", "Sina", "Baidu"]
var it=
{
info:["Tencent", "Sohu", "Sina", "Baidu"],
getinfo:function ()
{
alert (This.info.join (","));
}
};
var data=it.getinfo;
Data ();
Output: Qq,sohu,sina,baidu
Three. The "this" problem when calling as an object method
function test ()
{
alert (this.x);
}
var o={};
O.x=1;
O.t=test;
O.T ();
Output: 1
Four. The "This" problem when called as a constructor
var x=2;
function test ()
{
this.x=1;
}
Test ();
alert (x);
Output: 1
var x=2;
function test ()
{
this.x=1;
}
var o=new test ();
alert (o.x);
alert (x);
Output: 1,2
Five. Closure "This" points to the problem
var it=
{
info:["Tencent", "Sohu", "Sina", "Baidu"],
getinfo:function ()
{
function abc () {
alert ( This.info.join (","));
}
ABC ();
}
;
It.getinfo ();
Output: Error, TypeError:this.info is undefined
This in the closure does not point to it
Solving method
var it=
{
info:["Tencent", "Sohu", "Sina", "Baidu"],
getinfo:function ()
{
var _this=this;
Function abc () {
alert (_this.info.join (","));
}
ABC ();
}
;
It.getinfo ();
Advantage: Regardless of how the external function name (it) is changed, it can point to info
For more on JavaScript related content to view the site topics: "JavaScript object-oriented Tutorial", "javascript json operation tips Summary", "JavaScript switching effects and techniques summary", " JavaScript Search Algorithm Skills summary, javascript error and debugging skills Summary, JavaScript data structure and algorithm skills summary, JavaScript traversal algorithm and skills summary and JavaScript mathematical Operational Usage Summary
I hope this article will help you with JavaScript programming.