JavaScript Design Patterns and development note 2.this pointers

Source: Internet
Author: User

    • 1. Calling as an object method
    • 2. As a normal function call
      • 1. Calling as a normal function
      • 2. Assigning a function to an object
      • 3.callback internal this points to window
      • 4. Resolve this issue within the callback
    • 3. Constructor invocation
      • 1. Common constructors
      • 2. If the constructor appears to return an object of type objects
    • 4.function.prototype.call or Fucktion.prototype.apply call
      • 1. This can be dynamically passed to the function when compared to a normal function call
1. Calling as an object method
var obj = {    A:1,    geta:function() {        Console.log (this = = =obj);        Console.log (this. a);    }} Obj.geta ();

2. As a normal function call
//called as a normal functionvarname = ' Smartom ';varGetName =function(){    return  This. Name; Console.log (GetName ());//Back to undefined/*-------------------------------------------------------*///Assigning a function to a valuevarobj ={name:' Smartom ', GetName:function(){        return  This. Name; }}/*Assigning a function to an object is equivalent to Var getname=function () {ASDFASDF}*/varGetName =Obj.getname;console.log (GetName ());//Back to undefined/*=============== Please ignore the split line =============================*/varobj ={name:' Smartom ', GetName:function(){        return  This. Name; }}console.log (Obj.getname ()); //back to Smartom/*=============== I know you don't know ====================*/

Sometimes we encounter a problem, for example, in the div node event function, there is a local callback method, the callback method is called as a normal function, the callback internal this point to the window, 但我们往往认为他是指向该div的节点 as follows:

<! DOCTYPE html>document.getElementById (' Div1 '). onclick =function() {alert ( This. ID);//call Div1 as an object            varcallback =function() {alert ( This. ID); } callback (); //called the global this popup undefined        }    </script></body>

Workaround:

1. Assign this to a temporary variable

<! DOCTYPE html>document.getElementById (' Div1 '). onclick =function(){            varthat = This; alert (that.id); //call Div1 as an object            varcallback =function() {alert (that.id); } callback (); //called the global this popup undefined        }    </script></body>

2. Using strict mode "use strict" Note When using the this=undefined situation is ignored

3. Constructor invocation

There are no classes in JavaScript, but you can create objects from the constructor and also provide the new operator, which makes the constructor more like a class. is to construct an object with new, which looks more like a class

Typically, this in the constructor points to the returned object

var function () {    this. Name = ' Smartom ';}  var New MyClass (); Console.log (obj.name);   // back to Smartom

However, when using new to call the constructor, it is also important to note that if the constructor returns an object of Type objects , then the result of this operation will eventually return this object, not the one we expected before;

var function () {    this. Name = ' Smartom ';      return {        "Bob Dylan"    }}varnew  myClass (); Console.log (obj.name);   // return Bob Dylan

4.function.prototype.call and Function.prototype.apply calls

This can be dynamically passed into a function compared to a normal function call.

var obj1 = {    "Smartom",    function() {        return  this. Name;}    ; var obj2 = {    name:"Bob Dylan"};console.log (Obj1.getname ());         // output ' Smartom 'console.log (Obj1.getName.call (OBJ2));   // Output Bobdylan

JavaScript Design Patterns and development note 2.this pointers

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.