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.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer
JavaScript
中this
Points to the following situations:
- Ordinary function or as an object attribute
- Event binding
- Constructor
- Arrow function
-
call/apply/bind
Specify
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();
answer:
1. window 2. {name: 'OBJ', fn: function() {console.log(this)}} // obj 3. window
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();});
answer:
1. 200 2. 100 3. 点击button时:300 4. 鼠标移入button时:300 5. 鼠标移出时:200
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
<pre class='brush:php;toolbar:false;'>$button.click.call() // this为window,打印结果为100</pre>
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();
answer:
1. 200
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();answer:
1. {x:100, fn: function() {...}} // obj 2. window 3. {x:100, fn: function() {...}} // obj## 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: <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>
answer:
1. 100 2. 200 3. 200 4. 200
- call
- When executed, the first parameter is
this
points to, and the subsequent parameters arefn
The parameters during execution apply - At execution time, the first parameter is
this
points to , the subsequent parameters are an array composed of parameters duringfn
execution. Each item in the array will correspond to each parameter offn
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 tofn
, and the return value is a functionfixedThisFn
,fixedThisFn
will internally callfn
and specify itsthis
to point to for a deeper understanding# How does ##call/apply/bind
this points to in the function? Below we simulate and implement these three functions
Source code implementation
According to the previous introduction, we know that: when a function is called as an object property, this
points to the object that calls the functionconst obj = { x: 100, fn () {console.log(this);} }; obj.fn(); // {x: 100, fn: function() {...}} => obj
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
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; };
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
call method:
Syntax:
function.call(thisArg , arg1, arg2, ...)
*method as follows:thisArg
Optional. Thethis
value used when the
functionfunction is run. Note that
thismay not be the actual value seen by this method: if this function is in non-strict mode,
thennull
or undefinedis 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
function translateToObject (context) { // 可以通过 == 进行判断 context == null // null == undefined => 2个等号是成立的 // null,undefined => window if (typeof context === 'undefined' || context === null) { context = window; } else if (typeof context === 'number') { // 原始值转换为包装对象 context = new Number(context); } else if (typeof context === 'string') { context = new String(context); } else if (typeof context === 'boolean') { context = new Boolean(context); } return context; }
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; };
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; };
相比于call/apply
,bind
函数并没有立即执行函数,而是预先传入函数执行时的this
和参数,并且返回一个函数,在返回的函数中执行调用bind
函数并将预先传入的this
和参数传入
bind
的源码模拟:
Function.prototype.myOwnBind = function (context, ...outerArgs) { const fn = this; return function (...innerArgs) { return fn.call(context, ...outerArgs, ...innerArgs); }; };
精简版如下:
Function.prototype.myOwnBind = (context, ...outerArgs) => (...innerArgs) => this.call(context, ...outerArgs, ...innerArgs);
这里并没有实现通过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);
answer:
1. 1 2. 2 3. 什么都不输出 4. 1
这里我们根据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
更多编程相关知识,请访问:编程入门!!
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!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)