Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the use of this keyword in JavaScript

PHPz
Release: 2018-09-29 11:14:41
Original
1300 people have browsed it

This article mainly introduces the use of this keyword in JavaScript, which is the basic knowledge for getting started with JavaScript. Friends who need it can refer to it

Like many other object-oriented languages, JavaScript also has this keyword, this is used in functions to point to the object that calls this method. In actual programming, to determine who this points to, you can generally follow the following principles:

  • If the function is called by Function.call or Function.apply, then this points to the first element of call/apply parameter, 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, then this will point to the first parameter of bind (when the method is created).

  • If the function is called as a method by an object, then this points to this object.

  • If the function is just called as a function and is not attached to any object, then this points to the global variable window.

Function

First, let’s look at “function”:

function introduce() {
   alert("Hello, I am Laruence\r\n");
}
Copy after login

For, this function, this Who does the keyword point to?

A function defined globally, the owner of the function is the current page, that is, the window object.

This is why, I put the function in quotes. Because the function defined globally is actually a method of the window object.

Therefore, we can call it directly through the function name, or we can call it through the window. method name. At this time, this in the method The keyword points to its owner: window object.

If we look at 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);
* }
*/
Copy after login

After reading the above code, you may think Since the global function is a method of the window object, and the global variable is an attribute of the window object (already mentioned in the Javasript scope), then the global variable can be accessed through the this keyword in the global function, right?

The answer is yes, if you call the introduce function, you will know me as Laruence.

Event handling function

Perhaps, you are confused about this keyword, Most of the reasons come from using functions (methods) in event processing.

<input id="name" type="text" name="name" value="Laruence" />
Copy after login

For example, we now need to display the value of the name input box when we click on the "name" input box. Then, you can write the following code:

function showValue() {
   alert(this.value);
}
document.getElementById(&#39;name&#39;).onclick = showValue;
Copy after login

The above code runs normally, but why? Doesn’t it mean that the this pointer of the function always points to the function owner? Doesn’t it mean that the owner of the global variable is the window object? What?

Haha, if you can think of this question, it means you are reading my article seriously. Otherwise, I suggest you read it from the beginning, otherwise you will still be confused after reading it~

Well, yes, for the above code, showValue is defined in the global object, so it seems that the problem can only occur when the onclick event is bound.

We know that everything in Js is Objects, functions and methods are also attributes of objects, but functions have executable internal attributes. Therefore, for the above code, when binding the processor to onclick, it actually binds the input box Dom object with the id of name Assign a value to the onclick attribute.

In other words, we give the function showValue Copy to the onclick attribute of the name input box object. If we look at the onclick at this time:

function showValue() {
   alert(this.value);
}
document.getElementById(&#39;name&#39;).onclick = showValue;
alert(document.getElementById('name').onclick);
/**
* output
* function showValue() {
* alert(this.value);
* }
*/
Copy after login

So, when When the event is triggered, the onclick method of the name input box will be called. At this time, the this keyword will naturally point to the name input box.

However, confusing things come, such as the following This way of writing:

function showValue() {
   alert(this.value);
}
<input id="name" type="text" name="name" value="Laruence" onclick="showValue()"/>
Copy after login

cannot run normally, why is that?

Well, because at this time, it is not an assignment, but a reference.

If We pay attention to two ways of writing onclick. You will find that for the previous method, we used:

dom.onclick = showvalue; //没有调用符
Copy after login

and for the previous method:

onclick = "showvalue()" //有调用符
Copy after login

This can also be used sideways reflects the difference between the two: for the former, it is assignment, while for the latter, it is reference. If we check the onclick attribute of the input box at this time, we get:

alert(dom.onclick);
/**
* output:
* function onclick() {
*  showValue();
* }
*/
Copy after login

Do you see the difference? Do you understand why?

Speaking of this, there is a very interesting example. You can try it under IE:

<img src="xxx" onerror="alert(1);} function hi() { alert(2); " />
Copy after login

Change the pointer of this

Well, now that we already know why, how can we make this point to the place we want to point to?

For the above event processing function, we can have the following A way to write:

dom.onclick = showValue();

dom.onclick = function() { alert(this.value) ;}

<input onclick="alert(this.value);" /> //想想刚才我们的引用,是如何把这句嵌入的.

dom.addEventListener(dom, showValue, false); //ff only
Copy after login

For situations where it is not an event processing function, we can use apply, or call, to change the pointer of this keyword.

For example:

var laruence = {
   name : &#39;laruence&#39;,
   age : 26,
   position : &#39;Senior PHP Engineer&#39;,
   company : &#39;Baidu.inc&#39;
};
function introduce() {
   alert(this.name);
}
introduce.call(laruence);
Copy after login

Example of function being called by Function.call:

var myObject = {
  sayHello : function() {
    console.log(&#39;Hi! My name is &#39; + this.myName);
  },
  myName : &#39;Rebecca&#39;
};
var secondObject = {
  myName : &#39;Colin&#39;
};
myObject.sayHello();         // logs &#39;Hi! My name is Rebecca&#39;
myObject.sayHello.call(secondObject); // logs &#39;Hi! My name is Colin&#39;
Copy after login

Example of function being called by Function.call:

var myName = &#39;the global object&#39;,
  sayHello = function () {
    console.log(&#39;Hi! My name is &#39; + this.myName);
  },
  myObject = {
    myName : &#39;Rebecca&#39;
  };
var myObjectHello = sayHello.bind(myObject);
sayHello();    // logs &#39;Hi! My name is the global object&#39;
myObjectHello(); // logs &#39;Hi! My name is Rebecca&#39;
Copy after login

Example of function being called by object:

var myName = &#39;the global object&#39;,
  sayHello = function() {
    console.log(&#39;Hi! My name is &#39; + this.myName);
  },
  myObject = {
    myName : &#39;Rebecca&#39;
  },
  secondObject = {
    myName : &#39;Colin&#39;
  };
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
sayHello();        // logs &#39;Hi! My name is the global object&#39;
myObject.sayHello();   // logs &#39;Hi! My name is Rebecca&#39;
secondObject.sayHello(); // logs &#39;Hi! My name is Colin&#39;
Copy after login

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. But doing so will change the value of this in the function and ultimately perform the wrong operation. For example:

var myNamespace = {
  myObject : {
    sayHello : function() {
      console.log(&#39;Hi! My name is &#39; + this.myName);
    },

    myName : &#39;Rebecca&#39;
  }
};

var hello = myNamespace.myObject.sayHello;

hello(); // logs &#39;Hi! My name is undefined&#39;
Copy after login

So, if you want to cache variables to save code, the correct way is to save only the object that calls that function:

var myNamespace = {
  myObject : {
    sayHello : function() {
      console.log(&#39;Hi! My name is &#39; + this.myName);
    },

    myName : &#39;Rebecca&#39;
  }
};

var obj = myNamespace.myObject;

obj.sayHello(); // logs &#39;Hi! My name is Rebecca&#39;
Copy after login

总之,有一个大原则:谁调用了那个函数,this 就指向谁。

以上就是本章的全部内容,更多相关教程请访问JavaScript视频教程

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template