A discussion of this pointer in JavaScript

Source: Internet
Author: User

JavaScript is a Java language with a lot of Java-like features, but it is only similar, there is still a great difference in real use. This pointer often makes a lot of beginners crazy, I have been puzzled, find a lot of information, today summed up here, hoping to help the latter to tame the obstacle faster. There are many articles on the web that explain this pointer, and I think the key to understanding this pointer is to master the four invocation patterns of functions in JavaScript. So what is called? Call refers to the use of "()" after any expression that produces a function value, OBJ.F () is called in this way, and OBJ.F is known as access.

One, method invocation mode:

In the call pattern, the function is called as an object method: Obj.fun (). When the function is called in this form, the this pointer is bound to the object that called the method, obj.

1 var myObj = {2   value:0, 3   increase:function () {4     this.value++; 5     console.log (this.value); 6   } 7} ; 8//This binds to the MYOBJ object on 9 myobj.increase (); MyObj2 = {   value:1013};14 myobj2.increase = myobj.increase;//myObj2 and myObj of increase point to the same function reference address//This binding Fixed to MyObj2 object on Myobj2.increase (); 11

So when you bind an event of an HTML element to a function, if you use the this pointer in a function, the this pointer is bound to that element.

1 var ele1 = document.getElementById (' id '), 2 ele1.addeventlistener (' Click ', Myobj.increase, False); 3//The binding is equivalent to 4 Ele1.onclick = myobj.increase;5//Event trigger is equivalent to invoking the click Method 6 Ele1.click (); As with the above myobj2.increase, if there is no value attribute in Ele1, the error will be

Second, the function call pattern:

When a function is not used as a method call, it is not passed a point syntax by an object, and it is invoked as a function. When a function is called in this mode, this is bound to the global object.

1 var value =-10; 2 var myObj = {3   value:0, 4   increase:function () {5     this.value++; 6     Console.log (this.value); 7   } 8} ; 9//This binds to the MYOBJ object on the Myobj.increase (); 111 var ginc = myobj.increase;13 ginc (); -9 this binds to the Window object

Therefore, it is important to pay special attention to the use of intrinsic functions in the method, which is not bound to the MyObj object in the following example in the other function.

var value = -10;var myObj = {  value:0,  increase:function () {    this.value++;    Console.log (this.value);    var other = function () {      this.value++;      Console.log (This.value);     };    Other ();//-9, at which point the this in other is bound to the Window object  }};//This binds to the MyObj object Myobj.increase (); 1var ginc = Myobj.increase;ginc (); -8/////////////////1//-9//-8//-7

Fortunately, we can access the MyObj object in other ways using the following method:

1 var myObj = {2   value:0, 3   increase:function () {4     this.value++; 5     console.log (this.value); 6
   
    var that = this; 7     var other = function () {8       that.value++; 9       console.log (that.value);     };11 other     ();//-9, Then the this in other is bound to the Window object on the   }13};14//This binds to the MYOBJ object on page myobj.increase (); 116//////////////17//118//2
   

As an important part of browser compatibility: The Element.attachevent bound event method, when triggered by the this pointer is not bound to the element object, but bound to the Window object, because in IE, when the event is triggered, the response function is an independent function called function call pattern to tune Use the

Third, constructor mode invocation:

If you precede a function with a new call, it becomes a constructor-mode call. Using the new operator results in an object that is connected to the function prototype, and the this pointer is bound to the new object.

1 var p = function (n) {2   this.name = n;3}4 p.prototype.getname = function () {5   console.log (this.name); 6}7 var P = New P (' Woodtree '); At this point p in the This object Bai bound P point to the object reference on 8 p.getname ();//Woodtree

The new operator also changes the return value of the function. Calling P () in function call mode returns undefined, and a new object is returned through the new operator. The new operator resembles the following Function.prototype.create function:

1 var P = function (n) {2   this.name = n; 3} 4 p.prototype.getname = function () {5   console.log (this.name); 6} 7 VA R p = new P (' Woodtree '); 8 P.getname (); 9 Object.prototype.create = Object.create | | function (proto) {one   var f = function () {};12   f.prototype = proto;13   return new F (); 14}15 16 Function.prototype.create = function () {$   var that = object.create (this.prototype);   var obj = this.apply ( that, arguments);   return obj | | that;21}22 var p2 = p.create (' Hello new '); P2.getname (); Hello New

Four, apply, call mode invocation:

The function object in JavaScript inherits from object and can also have methods. Call and apply allow us to select the binding object for this. The difference between the two methods is that the second argument must be an array or a class array object that has the length property (arguments, NodeList, htmlelementcollection, and so on). The call is preceded by a comma interval, except for the first parameter, which is the object to bind this, followed by countless arguments.

1 var P = function (n) {2   this.name = n; 3} 4 p.prototype.getnameandage = function (age) {5   console.log (THIS.name + Age); 6} 7  8 P.prototype.getnameandage.call ({9   name: ' Catboat '), P.prototype.getnameandage.apply ({12   name: ' Lanuch ' 13}, [99];

By using the Apply and call methods, we can implement the BIND function in ES5 by ourselves.

1 var P = function (n) {2   this.name = n; 3} 4 p.prototype.getnameandage = function (age, Age2) {5   Console.log (this). Name + age + age2); 6} 7  8 P.prototype.getnameandage.call ({9   name: ' Catboat '), P.prototype.getnameandage.apply ({12   name: ' Lanuch ', [[+]]; Function.prototype.bindContext = Function (that) {   var _method = this,17   Slice = array.prototype.slice,18   args = slice.call (arguments, 1);   return function () {     _method.apply (That, Array.prototype.concat.apply (args, arguments));   }23};24 var f1 = P.prototype.getnameandage.bindcontext ({-   name: ' barque '), F1 (9);

We can also solve the this pointer problem when the event is triggered in IE (the following code is from the JavaScript framework Design):

1 var addevent = Document.addeventlistener? Function (el, type, FN, capture) {2   return El.addeventlistener (type, FN, capture); 3}: Function (el, type, fn) {4   El . attachevent (' on ' + type, Fn.bindcontext (El, Event)); 5}

A discussion of this pointer in JavaScript

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.