Today, I accidentally saw an article about this in JS, which is full of questions...
The author uses this. xxproperty to obtain some attributes and obtains a series of unexpected results such as undefined.
So I think this is caused by the previous assignment of this. propertyx, which changes the result of this...
Okay...
I. This
Check this code
Of course, it is very easy to get the information of the button Dom node.
The above code passes this and can be processed as a parameter.
Of course, there are other seemingly more decent methods.
But I have to admit that the error code caused by this will still be very easy to come in.
See the following code.
It is easy to write such code... The expected result must be my paramters input from alert, but it is actually undefined.
In fact, the error here is the synthesis of the above two cases. Here alert (this. Par); this in is the button instead of the test_handler instance.
2, call
Let's take a look at the simplest example.
There are four calls above. Understanding this in the calculate method is the key to getting the correct answer.
First time: this is 1, this. First = undefined for multiplication, of course, Nan is obtained.
Second: This is {First: 10}
Third time :.....
In fact, we can see that after using call, we can easily change the content of this, can you think of calling this in the first part of this for some time to avoid the mistakes I made because I didn't know what this was? The answer is yes, but check apply first.
3, apply
In fact, this is similar to the call. modify the code in the call just now. What if we want to calculate the product of 3 instead of 2 numbers?
Well, the second parameter of apply is an array, which is not easy to call.
4, bind
Well, with call and apply, I am trying to modify the code in the first part. To avoid obfuscation of this content, so what I want to display is to pass this in the first parameter of the call.
Take a look at the code
The problem occurs again. The instance is passed in. You can also use alert to get what you want, but I have to load addhandler when I load the window, in this way, the direct call will cause my function to be executed directly during page load, and the alert information will be sent out directly. There is more than a JS error...
It seems that I can't think of it here. I don't know how to solve it... So we came up with a new method bind.
To put it simply, the BIND function is to bind an instance to a method. Obviously, after the BIND takes effect, this inside the method will all become the instance that was previously bound, so there will be no confusion.
It's not too early. Check the modified Code.
Note that the comments in the above Code are two alert results in two cases, which is exactly the same as expected. Through bind, we simply implement the display and pass instance