JavaScript in this detailed _javascript tips

Source: Internet
Author: User
Tags anonymous

It is said that JavaScript is a very flexible language, which can also be said that it is a confusing language. It combines functional programming with object-oriented programming, plus dynamic language features that are incredibly powerful (in fact, cannot be compared to C + +, ^_^).

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 is in JS.

is created inside a function
object to which the function is bound when the call occurs (a mouthful)
This cannot be assigned, but can be changed by call/apply

Before using this, often worry about, not practical, you do not know who it is pointing to? Here, make a list of all the places it uses.

This and the constructor
This and objects
This and functions
This for the global environment
This and dom/events
This can be changed by call/apply
New bind and this in ES5
ES6 arrows Function (arrow functions) and this

1. This and the builder

This itself is what is needed in the constructor when the class is defined, and it is natural to be with the constructor.

/** *
 @class Tab *
 @param nav {string} The class
 * @param content {string} page contents
 *
   */
function Tab (nav, content) {
  This.nav = nav
  this.content = content
}
 
Tab.prototype.getNav = function () {return
  this.nav;
};
Tab.prototype.setNav = function (NAV) {
  this.nav = nav;
};
Tab.prototype.add = function () {
};

According to JavaScript's custom, this should hang the attribute/field, and the method should be on the prototype.

2. This and objects

JS objects can also be created without classes, some people may be strange, the class is the object template, objects are from the template copy out, no class how to create objects? JS really can, and you can write tens of thousands of lines of functional code without having to write a class. What OOP says is object-oriented programming, and it doesn't say class-oriented programming, right ^_^.

var tab = {
  nav: ',
  content: ',
  getnav:function () {return
    this.nav;
  },
  Setnav: function (n) {
    This.nav = n;
  }
}

3. This and functions

First of all, this and the independent functions are not meaningful to be put together, as mentioned before this should be related to object-oriented. Pure functions are only a low-level abstraction, encapsulation and reuse. As follows

function ShowMsg () {
  alert (this.message)
}
showmsg ()//undefined

Define SHOWMSG, and then invoke it as a function, this.message is undefined. So resolutely eliminate the use of this in pure functions, but sometimes it is written in a way that invokes the use of call/apply

function ShowMsg () {
  alert (this.message)
}
 
var m1 = {message
  : ' Incorrect phone number entered '
}
var m2 = { Message
  : ' The ID number entered is incorrect '
}
 
Showmsg.call (M1)//' Input phone number incorrect '
showmsg.call (m2)//' Input ID number is incorrect '

In this way, you can save a bit of code, such as when two classes/objects have altogether similar methods, you don't have to write two copies, just define one and then bind it to their own prototypes and objects. In fact, you are still using objects or classes (mode 1/2), only indirectly.

4. This for the global environment

This is referred to as "the object that is bound to the function at the time of the call", which is clumsy but absolutely correct and does not have an extra word. There are different host objects in the global environment, windows in the browser environment, and global in the node environment. Here is the key to the browser environment in this.

Inside non-function in browser environment this points to window

Alert (window=== this)/true
So you'll see a lot of open source JS Lib so write

(function () {
// ...

}) (this);
or write like this

(function () {
// ...

). Call (this);
For example underscore and requirejs, the effect is to the global variable window into the anonymous function cache, to avoid direct access. As for why to cache, this is related to the JS scope chain, read the more outer identifier performance will be worse. Please refer to the relevant knowledge, and then pull away.

Deceptive in the browser, variables declared directly within a non function by default are global variables and are hung by default as properties.

The var Andy = ' Andy Lau '
alert (andy = = Window.andy)//True
alert (andy = = This.andy)//True
alert (Window.andy = = T His.andy)//True

Because of this characteristic, some questions like

var x = ten;
function func () {
  alert (this.x)
}
var obj = {
  x:20,
  fn:function () {
    alert (this.x)
  }< c14/>}
var fn = Obj.fn
func ()//
FN ()//10

Yes, the final output is 10 of the global. Always keep this in mind: this is window, when you determine who is pointing to this, and when the execution is undefined, as long as the function is not bound to be invoked on the object.

5. This and dom/events

The consortium implements the DOM as a variety of nodes, nested together to form DOM tree. Nodes have different types, such as text nodes, element nodes and more than 10 kinds. Element node is divided into a lot of people who write HTML is very familiar with the tag (tag), such as Div,ul,label. Look at the API documents of the Interface,extends, you will find that it is completely in accordance with the object-oriented approach to implement a variety of APIs, such as the. Such as

See, this is written in Java, since it is an object-oriented implementation of the API, there must be class/object (nonsense ^_^), there are classes/objects, there must be this (do not forget the central theme of this article). All HTML tag classes are named like Htmlxxxelement, such as

Htmldivelement
Htmllabelelement
Htmlinputelement
...
As I said before this is an instance object to the current class, and for these tag classes, this is used internally by many methods that do not look at their source. With this conclusion, when writing HTML and JS, this is a lot clearer.

Example A

<!--this point to div-->
<div onclick= "alert (this)" ></div>

Example B

<div id= "nav" ></div>
<script>
  nav.onclick = function () {
    alert (this)//point to Div#nav
  }
</script>

Example C

$ (' #nav '). On (' click ', Function () {
  alert (this)//pointing to Nav
})

The above three examples show that when you add an event to an element node, the response function (handler) executes with this point to the element node itself. jquery is also consistent with the standard, but it is confusing, as "this points to the object that is bound by the function at call time", this in the jquery event handler should point to the JQuery object, not the DOM node. So you'll find that when you use jquery, it's often necessary to move the element in the event handler into a jquery object after being wrapped with $. Like what

$ (' #nav '). On (' click ', Function () {
  var $el = $ (this)//again to jquery object, if this is better $el for jquery objects
  . attr (' Data-x ', x)
  $el. attr (' Data-x ', x)
})

Some people may have the following questions

<div id= "nav" onclick= "getId ()" >ddd</div>
<script>
  function getId () {
    alert ( this.id)
  }
</script>

After clicking on the Div, why is the ID undefined, not to mention the current element div that points to? If you remember the words mentioned above, it is very clear why is undefined, put this sentence again.

To determine who is pointing to this, to see if execution is not defined, this is the window when the function is not bound to be invoked on the object.

Here the function GetId call is not bound to any object, it can be understood as this structure

Div.onclick = function () {
  getId ()
}

This is the div in the anonymous function of getId, but the this in the getId itself is not. Of course there is a hole in the ES5 strict mode.

6. This can be changed by call/apply

Call/apply are two other ways to function calls, and the first parameter of both can change the context of this function. Call/apply is the characterization of dynamic language characteristics in JS. The definition of dynamic language popularity

The program can change its structure when it is run, new functions can be introduced, and existing functions can be deleted, that is, the program can be changed at runtime.

Typically, there are several characteristics that indicate that it is a dynamic language

Dynamic Data types
Dynamic function execution
Dynamic method overrides
Dynamic languages are developed from the world's second language LISP, such as the Dead Smalltalk/vb, the currently alive Perl/python, and the popular ruby/javascript. The Dynamic Data type in JS is weakly typed, and the type of identifier is analyzed when it is executed. function dynamic execution manifests as eval,call/aply. Method overrides are embodied in the prototype rewrite. Do not pull far, here the emphasis on the impact of this call/apply.

var m1 = {Message
  : ' It is A '
} 
var m2 = {Message
  : ' This is B '
} 
 
function ShowMsg () {
  alert (this.message)
}
 
ShowMsg ()//undefined
Showmsg.call (M1)//' This is A '
showmsg.call (m2)//' The ' is B '

You can see that a separate call to ShowMsg returns a undefined that makes sense only if it is executed on an object that has a message property. With the imagination extended, if you write some common functions, you can bind to the prototype of multiple classes, so that the dynamic to add some methods to the class, but also save the code. This is a powerful function, but also dynamic language expression of strong expression.

People who turn to Ruby or Python often hear about "the fun of programming," a fun that comes from moving languages closer to people's thinking (rather than machine thinking) and more in line with business processes than project implementation processes. As a function, a dynamic language can be implemented with a smaller amount of code. Dynamic language is the main reason for the improvement of Programmer's productivity.

Performance, dynamic language does not have much advantage, but the idea of dynamic language is: To optimize the time of people rather than machine time. Improve developer productivity by sacrificing some of the program's performance or buying higher-profile hardware. With the continuous development of IT industry and the role of Moore's law, hardware relative to human parts has been devalued, this concept has a reasonable realistic basis.

JS in the call/apply in any popular Lib will be used, but almost two functions

Implement OOP with writing tools such as MooTools, Classjs, Class.js,
Fix this in the DOM event, such as JQuery, Events.js

About call and apply reuse: using apply and arguments multiplexing methods

About the performance of call and apply reference: Redundancy swap performance-from Backbone's triggerevents.

7. New bind and this in ES5

Above 6 mentioned call/apply in JS embodies dynamic language characteristics and dynamic language of the popular reason, its use in JS so wide. ES5 when it is released, it introduces a more advanced method of bind.

var modal = {Message
  : ' This is A '
}
 
function ShowMsg () {
  alert (this.message)
}
 
var Othershowmsg = Showmsg.bind (modal)
othershowmsg ()//' This is A '

Because it is ES5, the lower version of IE does not support, you can repair the next function.prototype. Bind is only the advanced version of Call/apply, and nothing else is special.

8. ES6 arrows function (arrow functions) and this

ES6 in this year's June 18 official release (the same day, the Chiapas East store Celebration, ^_^), it brings another type of function-arrow function. An important feature of the arrow function is to subvert the above sentence and post it again.

To determine who is pointing to this, to see if execution is not defined, this is the window when the function is not bound to be invoked on the object.

Yes, the preceding sentence has been used to determine the point of this, and the first half of the arrow function fails. The characteristic of the arrow function is, where is the definition, this is pointing to that. That is, the arrow function is defined in an object, and the This in the arrow function points to the object. As follows

var book = {
  author: ' John resig ',
  init:function () {
    Document.onclick = EV => {
      alert (this.author); /This is not a document here}}
;
Book.init ()

Object book has a property author, there is an Init method that adds a click event to the document, and if it's a traditional function, we know that this point should be document, but the arrow function points to the current object book.

The arrow function lets JS return to nature and simplicity, the function defines where it points to, defined in the object it points to the object, defines it on the prototype of the class, and points to an instance of the class, which is easier to understand.

Summarize:

The context of the function this is not too good to understand JS, the JS function itself has a variety of uses. The aim is to implement various language paradigms (object-oriented, functional, dynamic). This essence is not related to object-oriented, to write classes, object associations, and "functional". If you're using procedural functional development, you won't be able to use this one at all. But in the browser-side development is unavoidable to use this, because the browser object model (DOM) itself in object-oriented development, TAG implementation as a class, the class method will naturally refer to the other methods of the class, the way of reference is bound to use this. When you add an event to a DOM object, the callback function references that object only with this.

You get it?

Believe that after reading the full text, this is no longer a pit ~

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.