Table of Contents
Ordinary functions or as Object attributes
event binding
call/apply/bind( new Fn)
arrow function
#call/apply/bindChange this to point to as the first parameter passed in to
Source code implementationAccording to the previous introduction, we know that: when a function is called as an object property, this
Home Web Front-end JS Tutorial Where does JavaScript this point to?

Where does JavaScript this point to?

Jun 15, 2021 pm 04:27 PM
javascript this

This points to: 1. Ordinary function or as an object attribute, pointing to the window object; 2. In event binding, pointing to the element of the bound event; 3. In the constructor, pointing to the instance of the class; 4. Arrow In the function, it points to this in its nearest parent context; 5. In call/apply/bind, it points to the first parameter passed in.

Where does JavaScript this point to?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer

JavaScriptthisPoints to the following situations:

  • Ordinary function or as an object attribute
  • Event binding
  • Constructor
  • Arrow function
  • call/apply/bindSpecify

Let’s introduce one by one

Ordinary functions or as Object attributes

this depends on whether there is a "dot" before the method execution. If there is a "dot", whoever is in front of the "dot" this will be , if there is no dot, this points to window

const fn = function () {
  console.log(this);
};

const obj = { name: 'OBJ', fn };

fn();

obj.fn();

const fn1 = obj.fn;
fn1();
Copy after login

answer:

1. window
2. {name: 'OBJ', fn: function() {console.log(this)}} // obj
3. window
Copy after login

You can see that when the function is called as a property of the object, Its this points to the object that called the function, otherwise its this points to the window

event binding

When performing event binding, this in the event binding function is the element of the binding event:

// 假设页面中有id为button的button元素
// var x = 100;
window.x = 100;
const fn = function () {
  console.log(this.x);
};
const obj = { x: 200, fn };
const $button = document.getElementById('button');
$button.x = 300;

obj.fn();
const fn1 = obj.fn;
fn1();

$button.addEventListener('click', fn);
$button.addEventListener('mouseenter', obj.fn);

$button.addEventListener('mouseleave', function () {obj.fn();});
Copy after login

answer:

1. 200
2. 100
3. 点击button时:300
4. 鼠标移入button时:300
5. 鼠标移出时:200
Copy after login

But you need to pay attention The thing is, here we are when the user clicks, the browser helps us point the this of the click event to the DOM element bound to the event. If the corresponding event is triggered through code, we can specify its this<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>$button.click.call() // this为window,打印结果为100</pre><div class="contentsignin">Copy after login</div></div>

constructor through

call/apply/bind( new Fn)

The constructor (new Fn) is executed. this in the function is an instance of the current class, which is The new keyword helps us do it:

var x = 100;
const Fn = function () {
  this.x = 200;
  console.log(this.x);
};

const fn = new Fn();
Copy after login

answer:

1. 200
Copy after login

arrow function

There is no own ## in the arrow function #this, the this used is this

const fn = function () {
  console.log(this);
  setTimeout(() => {
    console.log(this);
  }, 1000);
  setTimeout(function () {
    console.log(this);
  });
};

const obj = { x: 100, fn };

obj.fn();
Copy after login

answer:

1. {x:100, fn: function() {...}} // obj
2. window
3. {x:100, fn: function() {...}} // obj
Copy after login

## in its nearest parent context

#call/apply/bindChange this to point to as the first parameter passed in to

call/apply/bind

i.e. is the this of the function: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>var x = 100; const obj = { x: 200, y: 200 }; const fn = function () { console.log(this.x); }; fn(); fn.call(obj); fn.apply(obj); const fixedThisFn = fn.bind(obj); fixedThisFn();</pre><div class="contentsignin">Copy after login</div></div>answer:

1. 100
2. 200
3. 200
4. 200
Copy after login

    call
  • When executed, the first parameter is this points to, and the subsequent parameters are fnThe parameters during execution
  • apply
  • At execution time, the first parameter is this points to , the subsequent parameters are an array composed of parameters during fn execution. Each item in the array will correspond to each parameter of fn
  • bind
  • When executing, the first parameter is the pointer passed in this in advance, and the subsequent parameters are the parameters passed in before the actual call to fn, and the return value is a functionfixedThisFn, fixedThisFn will internally call fn and specify its this to point to
  • for a deeper understanding# How does ##call/apply/bind
change what

this points to in the function? Below we simulate and implement these three functions

call/apply/ bind

Source code implementationAccording to the previous introduction, we know that: when a function is called as an object property, this

points to the object that calls the function

const obj = { x: 100, fn () {console.log(this);} };
obj.fn(); // {x: 100, fn: function() {...}} => obj
Copy after login
Using this feature of JavaScript

, we can use the executed function as the attribute of the first parameter

context of call/apply, and then pass context To call the function corresponding to this attribute, the this of the function points to the contextcall

source code simulation is as follows:

Function.prototype.myOwnCall = function (context, ...args) {
  const uniqueKey = new Date().getTime();
  // this为调用call方法的函数
  context[uniqueKey] = this;
  // 作为对象的方法被对象调用,this指向该对象context
  const result = context[uniqueKey](...args);
  delete context[uniqueKey];
  return result;
};
Copy after login
At this point, some friends may have discovered that what if the context

passed in to

call/apply is not an object? First let’s look at mdn

’s description of the first parameter of the

call method: Syntax: function.call(thisArg , arg1, arg2, ...)

* thisArg
Optional. The this value used when the
function function is run. Note that this may not be the actual value seen by this method: if this function is in non-strict mode, then null or undefined is specified It will be automatically replaced to point to the global object, and the original value will be wrapped Next, we process the first parameter of the
myOwnCall
method as follows:

function translateToObject (context) {
  // 可以通过 == 进行判断 context == null
  // null == undefined  => 2个等号是成立的
  // null,undefined => window
  if (typeof context === &#39;undefined&#39; || context === null) {
    context = window;
  } else if (typeof context === &#39;number&#39;) { // 原始值转换为包装对象
    context = new Number(context);
  } else if (typeof context === &#39;string&#39;) {
    context = new String(context);
  } else if (typeof context === &#39;boolean&#39;) {
    context = new Boolean(context);
  }
  return context;
}
Copy after login
calls this function in the myOwnCall

method: The implementation of

Function.prototype.myOwnCall = function (context, ...args) {
  context = translateToObject(context);
  const uniqueKey = new Date().getTime();
  // this为调用call方法的函数
  context[uniqueKey] = this;
  // 作为对象的方法被对象调用,this指向该对象context
  const result = context[uniqueKey](...args);
  delete context[uniqueKey];
  return result;
};
Copy after login
apply

is basically the same as

call, except for the second The parameter is an array:

Function.prototype.myOwnBind = function (context, paramsArray) {
  context = translateToObject(context);
  const uniqueKey = new Date().getTime();
  // this为调用call方法的函数
  context[uniqueKey] = this;
  // 作为对象的方法被对象调用,this指向该对象context
  const result = context[uniqueKey](...paramsArray);
  delete context[uniqueKey];
  return result;
};
Copy after login

相比于call/applybind函数并没有立即执行函数,而是预先传入函数执行时的this和参数,并且返回一个函数,在返回的函数中执行调用bind函数并将预先传入的this和参数传入

bind的源码模拟:

Function.prototype.myOwnBind = function (context, ...outerArgs) {
  const fn = this;
  return function (...innerArgs) {
    return fn.call(context, ...outerArgs, ...innerArgs);
  };
};
Copy after login

精简版如下:

Function.prototype.myOwnBind = (context, ...outerArgs) => (...innerArgs) => this.call(context, ...outerArgs, ...innerArgs);
Copy after login
这里并没有实现通过new操作符来执行fn.bind(context)的操作,如果想知道其详细的实现过程,可以看我的这篇文章: JS进阶-手写bind

在深入理解call/apply/bind的实现原理后,我们尝试完成下面的测试:

function fn1 () {console.log(1);}
function fn2 () {console.log(2);}
fn1.call(fn2);

fn1.call.call(fn2);

Function.prototype.call(fn1);
Function.prototype.call.call(fn1);
Copy after login

answer:

1. 1
2. 2
3. 什么都不输出
4. 1
Copy after login

这里我们根据call的源码来进行推导一下Function.prototype.call.call(fn1),其它的执行过程类似:

// 1. 首先会将Function.prototype.call作为一个函数来执行它原型上的call方法
// 所以call方法内部:
//    this => Function.prototype.call
//    context => fn1
// 通过对象的属性来执行方法改变this指向
//    fn1[uniqueKey] = this(Function.prototype.call)
//    fn1[uniqueKey]() // 执行 Function.prototype.call方法,但是this是context
// 2. 在this为fn1的情况下执行Function.prototype.call方法
// 所以call方法内部:
//    this => fn1
//    context => window
// 通过对象的属性来改变this指向
//    window[uniqueKey] = fn1
//    window[uniqueKey]() // 执行fn1(),但是this是window
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Where does JavaScript this point to?. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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.

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).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles