Home  >  Article  >  Web Front-end  >  Summary of method calling and method triggering in JavaScript_Basic knowledge

Summary of method calling and method triggering in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:07:591251browse

In js, the this keyword is an interesting thing, but its direction often confuses beginners.

In fact, to understand this keyword, two issues need to be clarified - "method calling and method triggering"

Now let’s look at a piece of code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>function</title>
<script>
function showThis(){
  console.info(this);
}
  
function Test1(){
  this.f=showThis;
}
function Test2(){
  this.f=function(){
    showThis();
  }
}

showThis();//window
new Test1().f();//Test1  
new Test2().f();//window
</script>
</head>
<body>
</body>
</html> 

Line 20 prints out the window object, which is easy to understand, but line 21 prints out the instance object of Test1, while line 22 prints out the window object. Looking at the construction of Test1 and Test2, we found that method f eventually executed the showThis method. But the this point in showThis is different. This is because the f method in Test1 points directly to showThis, new Test1().f() directly calls the showThis method with the instance of Test1, and the caller is the instance of Test1. And new Test2().f() triggers the showThis method of the window object in the instance method f of Test2, where this points to the caller window rather than the instance of the triggerer Test2.

You can find it now. this points to the caller, and the trigger just pushes the caller to execute the specified method.

Statement:
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