Description of this object usage in JavaScript

Source: Internet
Author: User
Tags anonymous bind class definition

Let's look at what this difference points to in these situations:

1. This in the global code:

1 alert (This)//window<
This in the global scope will point to the global object, even window in the browser.

The code is as follows Copy Code
function Foocoder (x) {
this.x = x;
}
Foocoder (2);

alert (x);//global variable x value 2

Here this points to the Global object, window. In strict mode, it is undefined.

3. Method invocation as an object:

The code is as follows Copy Code

var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
Console.log (this.name + "says" + sth);
}
}
Person.hello ("Hello World");

Output foocoder says Hello world. This points to the person object, which is the current object.

4. As a constructor:

The code is as follows Copy Code

New Foocoder ();

This point inside the function points to the newly created object.

5. Internal function:

The code is as follows Copy Code

var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
var SayHello = function (sth) {
Console.log (this.name + "says" + sth);
};
SayHello (STH);
}
}
Person.hello ("Hello World");//clever coder says Hello World


In an intrinsic function, this is not bound to the outer function object as expected, but is bound to the global object. This is generally considered a design error for JavaScript language, because no one wants this to point to the global object in the internal function. The general approach is to save this as a variable, which is generally agreed to that or self:

The code is as follows Copy Code

var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
var that = this;
var SayHello = function (sth) {
Console.log (that.name + "says" + sth);
};
SayHello (STH);
}
}
Person.hello ("Hello World");//foocoder says Hello World


6. Use call and apply to set this:

The code is as follows Copy Code


Person.hello.call (Person, "the World");

Apply and call are similar, except that the subsequent arguments are passed through an array instead of being passed in separately. The method definition of both:

The code is as follows Copy Code

Call (Thisarg [, ARG1,ARG2, ...]); Parameter list, ARG1,ARG2, ...

Apply (Thisarg [, Argarray]); Parameter array, Argarray

Both are used to bind a function to a specific object, and naturally this will be explicitly set to the first argument.

Simple summary
Simply summing up the above points, you can find that only the 6th is confusing.
In fact, we can sum up the following points:
1. When a function is called as a method of an object, this points to the object.
2. When the function is called as a fade function, this points to the global object (when strict mode is undefined)
3. This in the constructor points to the newly created object
4. This in a nested function does not inherit this from the upper function, and if necessary, you can save this of the upper function with a variable.
The simple point to summarize is that if this is used in a function, it points to the object only if it is called directly by an object.

Obj.foocoder ();

Foocoder.call (obj, ...);

Foocoder.apply (obj, ...);

We may often write code like this:

The code is as follows Copy Code


$ ("#some-ele"). Click = Obj.handler;

If This,this is used in handler, will it be bound to obj? Obviously not, after the assignment, the function is executed in the callback, this is bound to the $ ("#some-div") element. This requires understanding the execution environment of the function. This article does not intend to dwell on the execution environment of the function, and can refer to the relevant introduction of the execution environment and scope chain in the JavaScript Advanced program design. Here to point out, understand the JS function of the execution environment, will better understand this.
So how can we solve the problem of callback function binding? A new method is introduced in ES5, bind ():

Fun.bind (thisarg[, arg1[, arg2[, ...)]]

Thisarg
When a bound function is called, this argument is referred to as this when the original function is run. The parameter is not valid when the binding function is invoked with the new operator.
Arg1, Arg2, ...
When the binding function is called, the parameters, plus the parameters of the binding function itself, are used as the parameters of the original function at run time .<

This method creates a new function, called a binding function, that takes the first argument of the Bind method when it is created as this, and the second and subsequent parameters of the Bind method, along with the parameters of the binding function runtime itself, call the original function in order as an argument to the original function.
It is obvious that the bind method can solve these problems well.

The code is as follows Copy Code
$ ("#some-ele"). Click (Person.hello.bind (person));

When the corresponding element is clicked, the output foocoder says Hello World


In fact, this method is also very easy to simulate, we look at the prototype.js in the bind method of the source code:

The code is as follows Copy Code

Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call (arguments), object = Args.shift ();
return function () {
Return Fn.apply (object,
Args.concat (Array.prototype.slice.call (arguments)));
};
};

See, I've read another article for you to summarize.

What's so confusing about using the various this in JavaScript?

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

The code is as follows Copy Code

<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:

The code is as follows Copy Code

<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:

The code is as follows Copy Code
<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:

The code is as follows Copy Code

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:

The code is as follows Copy Code
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:

The code is as follows Copy Code

  function Jsclass ()
  {
      this.m_text = ' division element ';
  & nbsp;   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:

The code is as follows Copy Code
<table width= "height=" >
<tr>
<td>
<div style= "width:expression (this.parentElement.width);
Height:expression (this.parentElement.height); " >
Division Element</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:

The code is as follows Copy Code

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

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

The result of the


Run 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 indeed the former, which is determined by the problem of the JavaScript variable scoping

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.