惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
A Helpful Algorithm to Determine "this" value in JavaScript
Dmitri Pavlutin · 2021-03-09 · via Dmitri Pavlutin Blog

Every JavaScript developer, including myself, has been struggling in understanding how this keyword works.

I've created a universal algorithm to help you determine the value of this keyword in any situation.

While I made the algorithm as accessible as possible, I recommend reading it multiple times and understand the related terms.

Also, I'll show you a step-by-step evaluation of the algorithm for example situations. Finally, try the homework exercises by yourself!

Note: If you don't understand the algorithm from the first time: that's expected! Get back to the post later and try again until you crack it.

Ready? Let's begin!

1. this algorithm

The formal definition of ThisValueOfFunction(func, invocationType) that returns this value a function func invoked in a certain way invocationType.

ThisValueOfFunction(func, invocationType):

  1. If func is a regular function, then

    1. If invocationType is as a constructor, then

      1. let newObject be the newly constructed object newObject = new func()
      2. return newObject
    2. Else if invocationType is indirectly, then

      1. let thisArg be the argument of func.call(thisArg) or func.apply(thisArg)
      2. return thisArg
    3. Else if invocationType is as a method, then

      1. let object be the object upon which func is invoked on object.func()
      2. return object
    4. Else if invocationType is regular, then

      1. If strict mode is enabled, then return undefined
      2. Else return globalObject
  2. Else if func is an arrow function, then

    1. If func is defined in the outermost scope, then return globalObject
    2. Else
      1. let outerFunc be the outer function of func
      2. return ThisValueOfFunction(outerFunc, outerInvocationType)
  3. Else if func is a bound function of an originFunc function, then

    1. let thisArg be the argument of func = originFunc.bind(thisArg)
    2. return thisArg
  4. Else if func is a constructor() method inside of a class SomeClass, then

    1. let instance be the instance of the class instance = new SomeClass()
    2. return instance

1.1 The terms used in the algorithm

The algorithm uses plenty of JavaScript terms. If you aren't familiar with something, expand and look at the explanation.

Arrow function

An arrow function is a function defined using the fat arrow syntax =>. Example of an arrow function:


const sum = (number1, number2) => {

return number1 + number2;

}


Bound function

A bound function is a function created from invoking the method myFunc.bind(thisArg, arg1, ..., argN) upon a function. Example of a bound function:


function originalFunction() {

// ...

}

const boundFunction = originalFunction.bind({ prop: 'Value' });


Regular function

A regular function is a simple JavaScript function defined using function keyword or using a shorthand definition on an object. Examples of regular functions:


function regularFunction(who) {

return `Hello, ${who}!`;

}

const object = {

anotherRegularFunction(who) {

return `Good bye, ${who}!`

}

};


constructor()

constructor() is a special method inside of a class that initializes the class instance.


class SomeClass() {

constructor(prop) {

this.prop = prop;

}

}


Outermost scope

The outermost scope is the top scope that doesn't have an outer scope.


// The outermost scope

let a = 1;

function someFunction() {

// someFunction() scope

// Not the outermost scope

let b = 1;

}


Outer function

The outer function contains another function within its scope.


// outerFunction() is the outer function of myFunction()

function outerFunction() {

function myFunction() {

}

}


Global object

The global object is the object that always exists in the global scope. window is the global object in a browser environment, global in Node environment.

Invocation

Invocation of a function is just calling the function with some arguments.


function sum(number1, number2) {

return number1 + number2;

}

sum(1, 3); // Invocation

sum.call({}, 3, 4); // Invocation

sum.apply({}, [5, 9]); // Invocation

const obj = {

method() {

return 'Some method';

}

};

obj.method(); // Invocation

class SomeClass {

constructor(prop) {

this.prop = prop;

}

}

const instance = new SomeClass('Value'); // Invocation


Constructor invocation

Constructor invocation happens when a function or class is invoked using new keyword.


function MyCat(name) {

this.name = name;

}

const fluffy = new MyCat('Fluffy'); // Constructor invocation

class MyDog {

constructor(name) {

this.name = name;

}

}

const rex = new MyDog('Rex'); // Constructor invocation


Indirect invocation

An indirect invocation of happens when a function is called using func.call(thisArg, ...) or func.apply(thisArg, ...) methods.


function sum(number1, number2) {

return number1 + number2;

}

sum.call({}, 1, 2); // Indirect invocation

sum.apply({}, 3, 5); // Indirect invocation


Method invocation

Method invocation happens when a function is invoked in a property accessor expression object.method().


const object = {

greeting(who) {

return `Hello, ${who}!`

}

};

object.greeting('World'); // Method invocation

object['greeting']('World'); // Method invocation


Regular invocation

Regular invocation happens when the sole variable containing the function is used for invocation func(...).


function sum(number1, number2) {

return number1 + number2;

}

sum(1, 4); // Regular invocation


Strict mode

Strict mode is a special mode imposed upon running JavaScript code having some special restrictions. The strict mode is enabled by adding 'use strict' directive at the start of the script or the top of the function scope.

2. Examples

Example 1


const myFunc = () => {

console.log(this); // logs `window`

};

myFunc();


Open the demo.

ThisValueOfFunction(myFunc, "regular")

myFunc is an arrow function: thus matching the point 2 in the algorithm. Also myFunc is defined in the outermost scope, matching the point 2.1.

The point 2.1 of the algorithm says return globalObject: meaning that this value inside myFunc is the global object — window (in a browser environment).

Example 2


const object = {

method() {

console.log(this); // logs { method() {...} }

}

};

object.method();


Open the demo.

ThisValueOfFunction(object.method, "as a method")

method(), while being a property of the object, is a regular function. The point 1 of the algorithm is matched.

object.method() is a method invocation because of the property accessor usage: thus the point 1.3 is matched.

Then, according to point 1.3, this value inside method() equals the owning object of the method invocation (object.method()) — object.

Example 3


function MyCat(name) {

this.name = name;

const getName = () => {

console.log(this); // logs { name: 'Fluffy', getName() {...} }

return this.name;

}

this.getName = getName;

}

const fluffy = new MyCat('Fluffy');

fluffy.getName();


Open the demo.

ThisValueOfFunction(getName, "as a method")

getName() is an arrow function, thus the point 2 of the algorithm is applied. Then the point 2.2 matches, because MyCat is the outer function of getName().

The point 2.2.2 says that this value inside getName() arrow function equals this value of the outer function: MyCat.

So, let's run the algorithm recursively again on MyCat function — ThisValueOfFunction(MyCat, "as a constructor").

ThisValueOfFunction(MyCat, "as a constructor")

MyCat is a regular function, thus the point 1 of the algorithm is applied.

Because MyCat was invoked as a constructor new MyCat('Fluffy'), the point 1.1 is applied. Finally, according to points 1.1.1 and 1.1.2, this value inside MyCat equals to the constructed object: fluffy.

And, returning back to the arrow function's point 2.2.2, this inside of the getName() equals this of the MyCat — which is finally fluffy.

3. Homework

The best way to understand the algorithm is by trying it yourself. Follow the 3 exercises in determining this value.

Exercise 1


const myRegularFunc = function() {

console.log(this); // logs ???

};

myRegularFunc();


How would the algorithm determine this value inside myRegularFunc()? Write the step-by-step evaluation.

Exercise 2


class MyCat {

constructor(name) {

this.name = name;

console.log(this); // logs ???

}

}

const myCat = new MyCat('Lucy');


How would the algorithm determine this value inside new MyCat('Lucy')? Write the step-by-step evaluation.

Exercise 3


const object = {

name: 'Batman',

getName() {

const arrow = () => {

console.log(this); // logs ???

return this.name;

};

return arrow();

};

}

object.getName();


How would the algorithm determine this value inside arrow() function? Write the step-by-step evaluation.

4. Summary

In this post, I presented a universal algorithm to determine the value of this inside of an invoked function.

While the algorithm might be challenging at first, if you understand the step-by-step examples, you will realize how easy is to apply the algorithm.

Struggle applying the algorithm for a certain situation? Describe your case in a comment below!