JavaScript in this detailed _javascript tips

Source: Internet
Author: User

Here's the theme is this, don't pull away. This is inherently simple and always points to the current instance of the class, this cannot be assigned a value. The premise is that this cannot be separated from the class/object, which means this is a common keyword in object-oriented languages. To say the extreme point, if you write JS using functional style, rather than object-oriented, all of your code this will be much less, not even. With this in mind, when you use this, you should be developing in an object/class way, otherwise this is just a side effect of the function call.

This in JavaScript is always confusing and should be one of JS's well-known pits. Personally also feel JS in this is not a good design, due to this late binding feature, it can be global object, current object, or ... Some people even use this because of the big hole.

In fact, if you fully mastered the working principle of this, nature will not go into these pits. Let's look at what this difference points to in these situations:

1. This in the global Code

Alert (this)
//window

This in the global scope will point to the global object, even window in the browser.

2. As a simple function call

function Foocoder (x) {
 this.x = x;
}
Foocoder (2);
alert (x);
Global variable x value is 2

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

3. Method calls as objects

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

New Foocoder ();

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

5. Internal function

var name = "Clever coder";
var person = {
 name: ' Foocoder ',
 hello:function (sth) {
  var SayHello = function (sth) {
   Console.log (t His.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:

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

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:

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.

Simply summarize

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, ...);

Further

We may often write code like this:

$ ("#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 arguments, along with the parameters of the binding function itself, are in order as arguments for the runtime of the original function.
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.

$ ("#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:

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

Believe that after reading the full text, this is no longer a pit ~, we all understand, for more information, please click on the website of cloud-dwelling community to learn.

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.