Home Web Front-end JS Tutorial Detailed test explanation of the problem pointed by this keyword in Javascript

Detailed test explanation of the problem pointed by this keyword in Javascript

Aug 11, 2017 am 10:34 AM
javascript this Keywords

This is a feature in Javascript that is very easy to misunderstand and then use incorrectly. Therefore, the following article mainly introduces to you the relevant information about the problem of this keyword pointing in Javascript. The test questions in the article test your familiarity with this. Friends in need can refer to it. Let's take a look together.

Preface

Javascript is an object-based dynamic language, that is to say, everything is an object. A typical example is that functions are also treated as ordinary objects. Javascript can implement object-oriented programming through certain design patterns, in which this "pointer" is a very important feature in realizing object-oriented programming. This article will give you a detailed introduction to the relevant content pointed to by the this keyword in Javascript. Let us do a small test first. If you get all the answers correct, congratulations, you don’t need to read any further.

Test questions

First question


<script>
 var str = &#39;zhangsan&#39;;

 function demo() {
  var str = &#39;lisi&#39;;
  alert(this.str);
 }
 window.demo(); // ??

 var obj = {
  str: "wangwu",
  say: function() {
   alert(this.str);
  }
 }
 obj.say(); // ??

 var fun = obj.say;
 window.fun(); // ??
</script>
Copy after login

Second question


<script>
 var username = &#39;zhangsan&#39;;

 (function() {
  var username = &#39;lisi&#39;;
  alert(this.username); // ??
 })()

 function demo() {
  var username = &#39;wangwu&#39;;

  function test() {
   alert(this.username);
  }

  test(); // ??
 }
 demo();
</script>
Copy after login

Third question


<script>
 function Person() {
  this.username = &#39;zhangsan&#39;;
  this.say = function() {
   alert(&#39;我叫&#39; + this.username);
  }
 }

 var p = new Person();
 p.say(); // ??

 var p1 = new Person();
 p1.say(); // ??
</script>
Copy after login

Question 4


##

<script>
 var username = &#39;zhangsan&#39;;

 function demo() {
  alert(this.username)
 }

 var obj1 = {
  username: "lisi"
 };
 var obj2 = {
  username: "wangwu"
 };

 demo(); // ??
 demo(obj1); // ??
 demo(obj2); // ??
 demo.call(obj1); // ?? 
 demo.apply(obj2); // ??
</script>
Copy after login

Answer

  • The first question: zhangsan wangwu zhangsan

  • The second question: zhangsan zhangsan

  • The third question: My name is zhangsan My name is zhangsan

  • The fourth question: zhangsan zhangsan zhangsan lisi wangwu

( Look down, there is a detailed analysis below)


this

  • points to the calling function Object

  • No object calling function/Anonymous function self-calling (this points to window)

  • Object generated through new

  • apply/call

#1. Point to the object of the calling function


<script>
 // this:指向调用函数的对象
 var str = &#39;zhangsan&#39;;

 function demo() {
  var str = &#39;lisi&#39;;

  //this->window
  console.log(this);
  alert(this.str);
 }
 window.demo(); // zhangsan

 var obj = {
  str: "wangwu",
  say: function() {
   // this->obj
   alert(this.str);
  }
 }
 obj.say(); // wangwu

 var fun = obj.say;
 window.fun(); // zhangsan
</script>
Copy after login

  • The global function (demo) belongs to the method of the window object. The window calls demo, so this points to the window

  • obj calls the say method, and this Pointing to obj

  • fun() is a global function, and the declared fun receives a simple function in obj and does not call it (obj.say() is the function that is called ), fun at this time is a function (function(){alert(this.str);}), then when fun() calls the function, this points to window

  • Who calls the function, then this points to who

## 2. Calling functions without objects/self-calling anonymous functions->this points to window


<script>
 // 2.匿名函数自执行|匿名函数|无主函数 this->window
 var username = &#39;zhangsan&#39;;

 // 匿名函数自执行 this->window
 (function() {
  var username = &#39;lisi&#39;;
  console.log(this); // window
  alert(this.username); // zhangsan
 })()

 function demo() {
  var username = &#39;wangwu&#39;;

  // 无主函数 this->window
  function test() {
   // this->window
   alert(this.username);
  }

  test(); // zhangsan
 }
 demo();
</script>
Copy after login

    Because the anonymous function has no name, it is attached to window
  • test(), Whoever calls test points to who. Of course, after experimenting, it is not called by window, nor is it called by demo. If no one cares about it, then it points to window. It is equivalent to a mainless function that has no owner calling it.
3. Objects generated through new


##
<script>
 // 3.通过new的对象:this指向产生的对象
 // 函数
 function Person() {
  // 属性
  this.username = &#39;zhangsan&#39;;
  // 方法
  this.say = function() {
   // this->p
   console.log(this); // Person对象
   alert(&#39;我叫&#39; + this.username);
  }
 }

 // 实例化出一个对象:p就具有了username属性和say方法
 var p = new Person();
 console.log(p); // Person对象
 console.log(p.username); // zhangsan
 p.say(); // 我叫zhangsan

 // this->p1
 var p1 = new Person();
 p1.say(); // Person对象 我叫zhangsan
</script>
Copy after login


When our function Person uses this format to write attributes and methods, then we must use new to make the attributes and methods valuable, and use new to use the attributes and methods in the function
  • 4. Apply/call call

First of all, let’s understand what apply()/call() is?

apply()/call(): The function is finally called, but the internal this points to thisObj

function.call([thisObj[,arg1[, arg2[, [,.argN]]]]])
function.apply([thisObj[,argArray]])
Copy after login


Note :


1. Call the function function, but this in the function points to thisObj (change the internal pointer of the object)

2. If thisObj is not passed parameter, the default is the global object

3. Contact and difference between call()/apply()

Contact: The function is the same, the first parameter is thisObj

Difference: If there are more parameters passed

The actual parameters of call() are listed one by one

The actual parameters of apply() The parameters are all placed in the second array parameter


An example of understanding apply()/call():

<script>
 // apply()/call()
 function demo() {
  console.log(123);
 }

 // 调用函数的时候,demo.call()/demo.apply()最终调用的还是demo()
 demo(); // 123
 demo.call(); //123
 demo.apply(); // 123
</script>

<script>
 // call()/apply()的区别:
 // call()参数单独再call中罗列
 // apply()的参数通过数组表示
 function demo(m, n, a, b) {
  alert(m + n + a + b);
 }
 demo(1, 5, 3, 4); // 13
 demo.call(null, 1, 5, 3, 4); // 13
 demo.apply(null, [1, 5, 3, 4]); // 13
</script>
Copy after login


The fourth usage example of this

<script>
 // this的第四个用法:call(obj)/apply(obj):强制性的将this指向了obj
 var username = &#39;zhangsan&#39;;

 function demo() {
  alert(this.username)
 }

 var obj1 = {
  username: "lisi"
 };
 var obj2 = {
  username: "wangwu"
 };

 // call()/apply():打劫式的改变了this的指向
 demo(); // zhangsan
 demo(obj1); //zhangsan
 demo(obj2); //zhangsan
 demo.call(obj1); // lisi 
 demo.apply(obj2); // wangwu
</script>
Copy after login


If you directly call what is written in the demo, whether it is obj1 or obj2, then demo is still called by window.
  • Whether you use call or apply, the demo function will eventually be called, but they will force this to point to obj1/obj2, and force this to point to their first parameter object.
Summarize

The above is the detailed content of Detailed test explanation of the problem pointed by this keyword in Javascript. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

In-depth analysis of the role and usage of the static keyword in C language In-depth analysis of the role and usage of the static keyword in C language Feb 20, 2024 pm 04:30 PM

In-depth analysis of the role and usage of the static keyword in C language. In C language, static is a very important keyword, which can be used in the definition of functions, variables and data types. Using the static keyword can change the link attributes, scope and life cycle of the object. Let’s analyze the role and usage of the static keyword in C language in detail. Static variables and functions: Variables defined using the static keyword inside a function are called static variables, which have a global life cycle

See all articles