In JavaScript, this is always pointing to the owner of a function or a method.
Function
Let's check out function first.
- function introduce() {
- alert("Hello, I am Laruence\r\n");
- }
For this function, what does this point to? In JavaScript, a global function's owner is the current page, i.e, the window object. Because its a method of the window object if we define a global function. Now you should know the this will point to the window object in the above function.
If we check the introduce property of window:
- var name = "I am Laruence";
- function introduce() {
- alert(this.name);
- }
- alert(window.introduce);
- /**
- * output:
- * function introduce() {
- * alert(this.name);
- * }
- */
When you call the introduce function, it will alert "I am Laruence".
Event handler
Maybe the biggest confusion about this keyword is coming from the event handler.
<input id="name"type="text"name="name"value="Laruence"/>
For example, if we want to show the value of the name field when we click this text field, we may add below codes:
- function showValue() {
- alert(this.value);
- }
- document.getElementById('name').onclick = showValue;
In above codes. the function showValue is defined in global scope, will this point to window? The answer depends. When you assign the showValue to onclick,it means you are assign this function to the method of document.getElementById("name"), now the whowValue becomes one method of it. So this will point to document.getElementById("name"). If we check the value of onclick, we will get:
- function showValue() {
- alert(this.value);
- }
- document.getElementById('name').onclick = showValue;
- alert(document.getElementById('name').onclick);
- /**
- * output
- * function showValue() {
- * alert(this.value);
- * }
- */
However if we write below code:
- function showValue() {
- alert(this.value);
- }
It will not run as expected. Why? Because now it's not an assignment, it's a call. Now if we check the value of onclick, we will get:
- alert(dom.onclick);
- /**
- * output:
- * function onclick() {
- * showValue();
- * }
- */
Change what this points to
We can use call or apply to change what this points to.
- var laruence = {
- name : 'laruence',
- age : 26,
- position : 'Senior PHP Engineer',
- company : 'Baidu.inc'
- };
- function introduce() {
- alert(this.name);
- }
- introduce.call(laruence);