This article mainly introduces the use of the this keyword in JavaScript, which is the basic knowledge in JavaScript beginners. You can refer to this keyword in JavaScript, which is the same as many other object-oriented languages, this is used to point to the object that calls this method in the function. In actual programming, the following principles can be followed to determine who this actually points:
- If the Function is called. call or Function. if the parameter is null or undefined, this points to the Global Object (in the browser, the global object is the window object ).
- If the Function is called by Function. bind, this points to the first parameter of bind (when the method is created ).
- If this function is called by an object as a method, this points to this object.
- If the function is called as a function and is not attached to any object, this points to the global variable window.
Function
First, let's look at the "function ":
function introduce() { alert("Hello, I am Laruence\r\n");}
For this function, who does this keyword point?
The global function is defined. The function owner is the current page, that is, the window object.
That's why I enclosed the function in quotation marks, because the global function is actually a method of the window object.
Therefore, we can use the function name for direct call, or use the window. method name for call. At this time, the this keyword in the method points to its owner: window object.
If we check the introduce attribute of window, we will get:
var name = "I am Laruence";function introduce() { alert(this.name);}alert(window.introduce);/*** output:* function introduce() {* alert(this.name);* }*/
After reading the above Code, you may think that, since the global function is the method of the window object, and the global variable is the attribute of the window object (already described in the scope of Javasript), then, you can use the this keyword to access global variables in global functions?
The answer is yes. If you call the introduce function, you will know that I am Laruence.
Event processing functions
Perhaps, most of the confusion about the this keyword comes from the use of functions (methods) in event processing.
For example, if you need to display the value in the name input box when you click "name", you can write the following code:
function showValue() { alert(this.value);}document.getElementById('name').onclick = showValue;
The above code runs normally, but why? Isn't this a function's this pointer always pointing to the function owner? Isn't the owner of global variables A window object?
Haha, if you can think of this question, it means that you are reading my article seriously. Otherwise, I suggest you read it from the beginning. Otherwise, you are confused ~
Well, for the above Code, showValue is defined as a global object, so it seems that the problem only occurs when the onclick event is bound.
We know that everything in Js is an object, and functions and methods are also attributes of objects, except that functions have executable internal attributes. therefore, for the above Code, when binding a processor to onclick, it is actually assigning values to the onclick attribute of the Dom object in the input box with id as name.
That is to say, we give the showValue Copy function to the onclick attribute of the object in the name input box. If we view the onclick at this time:
function showValue() { alert(this.value);}document.getElementById('name').onclick = showValue;alert(document.getElementById('name').onclick);/*** output* function showValue() {* alert(this.value);* }*/
Therefore, when an event is triggered, The onclick method of the name input box is called. At this time, the keyword "this" naturally points to the name input box.
However, confusing things come, such as the following:
function showValue() { alert(this.value);}
It cannot run normally. Why?
Well, at this time, it is not a value assignment, but a reference.
If we pay attention to the two onclick statements, you will find that for the previous method, we use:
Dom. onclick = showvalue; // No caller
But for the method just now:
Onclick = "showvalue ()" // a caller
This can also reflect the differences between the two: for the former, it is a value assignment, and for the latter is a reference. If we check the onclick attribute of the input box at this time, we get:
alert(dom.onclick);/*** output:* function onclick() {* showValue();* }*/
Have you seen the difference? Why?
Here is an interesting example. You can try it in IE:
Change the point of this
So, since we already know why, how can we point this to what we want?
For the above event processing functions, we can write the following statements:
Dom. onclick = showValue (); dom. onclick = function () {alert (this. value );}// Think about how our reference embedded this sentence. dom. addEventListener (dom, showValue, false); // ff only
For scenarios that are not event processing functions, we can use apply or call to change the point of this keyword.
For example:
var laruence = { name : 'laruence', age : 26, position : 'Senior PHP Engineer', company : 'Baidu.inc'}; function introduce() { alert(this.name);} introduce.call(laruence);
Example of a Function called by Function. call:
var myObject = { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca'};var secondObject = { myName : 'Colin'};myObject.sayHello(); // logs 'Hi! My name is Rebecca'myObject.sayHello.call(secondObject); // logs 'Hi! My name is Colin'
Example of a Function called by Function. call:
var myName = 'the global object', sayHello = function () { console.log('Hi! My name is ' + this.myName); }, myObject = { myName : 'Rebecca' };var myObjectHello = sayHello.bind(myObject);sayHello(); // logs 'Hi! My name is the global object'myObjectHello(); // logs 'Hi! My name is Rebecca'
Example of a function called by an object:
var myName = 'the global object', sayHello = function() { console.log('Hi! My name is ' + this.myName); }, myObject = { myName : 'Rebecca' }, secondObject = { myName : 'Colin' };myObject.sayHello = sayHello;secondObject.sayHello = sayHello;sayHello(); // logs 'Hi! My name is the global object'myObject.sayHello(); // logs 'Hi! My name is Rebecca'secondObject.sayHello(); // logs 'Hi! My name is Colin'
When calling a function in a deep namespace, we usually cache a variable pointing to the function to be called to reduce the amount of code. However, this will change the value of this in the function and eventually perform the wrong operation. For example:
var myNamespace = { myObject : { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' }};var hello = myNamespace.myObject.sayHello;hello(); // logs 'Hi! My name is undefined'
Therefore, to cache variables to save the amount of code, the correct method is to save only until the object that calls the function:
var myNamespace = { myObject : { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' }};var obj = myNamespace.myObject;obj.sayHello(); // logs 'Hi! My name is Rebecca'
In short, there is a big principle: who calls the function, this points to who.