Home>

I believe this keyword is very familiar to everyone,This key provided in js is more confusing than in oo language,This article introduces the understanding of this keyword in js through this article.

Regarding this, it is a compulsory question for many front-end interviews.Sometimes I see these topics online,Tried it myself,Um, really wrong! In actual development,You will also encounter this (although some libraries will help us deal with it), such as when using some frameworks,For example:knockout, sometimes I do n’t understand why I do n’t use this directly, but instead pass in this as a parameter.

Next you talk about my understanding of it,Also as a note,For future reference.There is something wrongComments are welcome.

1. Unlike c#, this must point to the current object.

This point of js is uncertain,In other words, it can be changed dynamically.call/apply is the function used to change this.This design makes the code more flexible,Higher reusability.

2. this In general,Both point to the owner of the function.

this point is very important! this point is very important! this point is very important!

This is also a common interview question.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>

Since the owner of the shownumber method is obj, this.number=3;this refers to the number attribute of obj.

Similarly, the second console.log also prints the attribute number.

Why the second point is that in general this refers to the owner of the function,Because there are special circumstances.Function self-execution is a special case,In function self-execution,This points to:window. So the first console.log prints the property number of window.

So add a bit:

3. In function self-executing,this refers to the window object.

Expansion. One more confusing thing about this is that in the dom event, there are usually three situations:

as follows:

1. Register events using tag attributes,At this point this refers to the window object.

<input type="button" value="button" onclick="test ()" />
  function test () {alert (this)}

2. For 1, to make this point to input, you can pass this as a parameter.

3. Register with addeventlistener etc. At this point this also points to input.

document.getelementbyid ("test"). addeventlistener ("click", test);

In object-oriented programming languages,We are very familiar with this keyword.For example, C++, C#, and Java all provide this keyword.Although it was more difficult at the beginning of learning,But as long as you understand,It is very convenient and meaningful to use.JavaScript also provides this keyword, but it is more "confusing" than the classic oo language.

Let ’s take a look.What's so confusing about using this in JavaScript?

1. Use the this keyword in the html element event attribute inline:

//can use this inside
">division element
 //can use this inside
 ">division element
</pre>
</div>
<p>
We generally use a more common method here:javascirpt:eventhandler (this), this form.
But you can actually write any valid javascript statement here, if you are happy to define a class here (but it will be an inner class). The principle here is that the script engine generates an anonymous member method of a div instance object.
And onclick points to this method.
</p>
<p>
<strong>
2. Use the this keyword in the event handler in dom mode:
</strong>
</p>
<div>
<pre>
division element
 var div=document.getelementbyid ("elmtdiv");
 div.attachevent ("onclick", eventhandler);
 function eventhandler ()
 {
 //use this here
 }
//->
division element
 var div=document.getelementbyid ("elmtdiv");
 div.attachevent ("onclick", eventhandler);
 function eventhandler ()
 {
 //use this here
 }
//->

At this time, the this keyword in the eventhandler () method indicates that the object is ie's window object. This is because eventhandler is just a normal function,For attachvent, the script engine's call has nothing to do with the div object itself.At the same time you can look at the caller property of eventhandler, it is equal to null. If we want to get a div object reference in this method,Should use:this.event.srcelement.

3. Use the dhtml method in the event handler function:

division element
lt;mce:script language="javascript">
var div=document.getelementbyid ("elmtdiv");
div.onclick=function ()
{
 //use this here
};
/->
division element
 var div=document.getelementbyid ("elmtdiv");
 div.onclick=function ()
 {
 //use this here
 };
//->

The content indicated by this keyword is a div element object instance,Using dhtml in the script to directly assign an eventhandler method to div.onclick is equivalent to adding a member method to the div object instance.The difference between this method and the first method is thatThe first method is to use the html method, and here is the dhtml method, the script parsing engine will no longer generate anonymous methods.

4. Use the this keyword in the 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 ();
 jc.tostring ();

This is the use of this in the javascript simulation class definition, and this is very familiar to other oo languages.However, it is required that member properties and methods must be referenced using the this keyword.Running the above program will tell that myname is undefined.

5. Add the this keyword in the prototype method for the internal object of the script engine:

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 () {}
 alert (foo.getname ());

Here this refers to the instance of the class to which the prototype was added,Similar to the class definition in 4,Nothing too special.

6, combined with 2&4, say a more confusing use of this keyword:

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 will talk about the results,After the page is run, it will display:"division element". After confirming, click on the text "division element" and it will display:"undefined".

7, the css expression using the this keyword:

height:expression (this.parentelement.height);">
 division element
 height:expression (this.parentelement.height);">
 division element

This is considered as the same as in 1.It also refers to the div element object instance itself.

8. Use the this keyword in internal 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;
 }
 outerfoo () ();

The result of the operation is:"inner name, outer name". As we explained in 2,If the result here is "inner name, undefined" seems more reasonable?But the correct result is indeed the former,This is due to the problem of javascript variable scope,For more details, please refer to "The original keyword" var "in jscript or the article" and the reply.

Which can be divided into two ways

(1) dom method-the result of this method is that this points to the window object

(2) dhtml method-the result of this method is that this points to the div element object instance

It should be noted,Functions are also objects,So you need to distinguish between variable definitions and member variable definitions,as follows:

view plaincopy to clipboardprint?
var variablename;//variable definition
//Scope:within the scope of the function definition
//Usage method:use variablename directly
this.varname;//Member variable definition
//Scope:within the scope of the function object definition and its member functions
//Usage method:this.varname
var variablename;//variable definition
//Scope:within the scope of the function definition
//Usage method:use variablename directly
this.varname;//Member variable definition
//Scope:within the scope of the function object definition and its member functions
//Usage method:this.varname
view plaincopy to clipboardprint?
    function jsclass ()
    {
      var vartext="func variable!";//Ordinary variables in functions
      this.m_text="func member!";//Member variable of function class
      this.m_element=document.createelement ("div");//member variable,Create a div object
      this.m_element.innerhtml=vartext;//Ordinary variables using functions
      this.m_element.attachevent ("onclick", this.tostring);//Connect a handler to the event of this object
      this.newelement=document.createelement ("div");
      this.newelement.innerhtml="new element";
      this.newelement.m_text="new element text!";//Create a member for the created object
      this.newelement.onclick=function ()
      {
        alert (this.m_text);//point to members of div object
      };
    }
    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 inside points to an instance of the jsclass class,There are m_text members
    }
//->
    initialize ();
//->
 function jsclass ()
  {
   var vartext="func variable!";//Ordinary variables in functions
    this.m_text="func member!";//Member variable of function class
    this.m_element=document.createelement ("div");//member variable,Create a div object
    this.m_element.innerhtml=vartext;//Ordinary variables using functions
    this.m_element.attachevent ("onclick", this.tostring);//Connect a handler to the event of this object
    this.newelement=document.createelement ("div");
    this.newelement.innerhtml="new element";
    this.newelement.m_text="new element text!";//Create a member for the created object
    this.newelement.onclick=function ()
   {
     alert (this.m_text);//point to members of div object
   };
  }
  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 inside points to an instance of the jsclass class,There are m_text members
  }
//->
   initialize ();
//->

The result of the above code execution is:

When the page loads,pop-up dialogue box,Output func member!

Show on page

func variable!
 new element

When you click func variable, a dialog box appears,Show undefined

-Because at this time the this pointer in the tostring function points to window

When you click new element, a pop-up dialog box displays new element text!

-Because the this pointer in the tostring function at this time points to the div element, which has an m_text member defined (this.newelement.m_text="new element text!")

  • Previous Wrong use of C # yield in WCF (2)
  • Next MySQL backup and recovery to ensure data consistency (5)