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

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

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 A Helpful Algorithm to Determine "this" value 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? 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
What's a Method in JavaScript?
Dmitri Pavlutin · 2021-02-02 · via Dmitri Pavlutin Blog

1. What is a method

Let's define and call a regular function:


function greet(who) {

return `Hello, ${who}!`;

}

greet('World'); // => 'Hello, World!'


The function keyword followed by its name, params, and body: function greet(who) {...} makes a regular function definition.

greet('World') is the regular function invocation. The function greet('World') accepts data from the argument.

What if who is a property of an object? To easily access the properties of an object you can attach the function to that object, in other words, create a method.

Let's make greet() a method on the object world:


const world = {

who: 'World',

greet() {

return `Hello, ${this.who}!`;

}

}

world.greet(); // => 'Hello, World!'


greet() { ... } is now a method that belongs to the world object. world.greet() is a method invocation.

Inside of the greet() method this points to the object the method belongs to — world. That's why this.who expression accesses the property who.

Note that this is also named context.

The context is optional

While in the previous example I've used this to access the object the method belongs to — JavaScript, however, doesn't impose a method to use this.

For this reason you can use an object as a namespace of methods:


const namespace = {

greet(who) {

return `Hello, ${who}!`;

},

farewell(who) {

return `Good bye, ${who}!`;

}

}

namespace.greet('World'); // => 'Hello, World!'

namespace.farewell('World'); // => 'Good bye, World!'


namespace is an object that holds 2 methods: namespace.greet() and namespace.farewell().

The methods do not use this, and namespace serves as a holder of alike methods.

2. Object literal method

As seen in the previous chapter, you can define a method directly in an object literal:


const world = {

who: 'World',

greet() {

return `Hello, ${this.who}!`;

}

};

world.greet(); // => 'Hello, World!'


greet() { .... } is a method defined on an object literal. Such type of definition is named shorthand method definition (available starting ES2015).

There's also a longer syntax of methods definition:


const world = {

who: 'World',

greet: function() {

return `Hello, ${this.who}!`;

}

}

world.greet(); // => 'Hello, World!'


greet: function() { ... } is a method definition. Note the additional presence of a colon and function keyword.

Adding methods dynamically

The method is just a function that is stored as a property on the object. That's why you can add methods dynamically to an object:


const world = {

who: 'World',

greet() {

return `Hello, ${this.who}!`;

}

};

// A a new property holding a function

world.farewell = function () {

return `Good bye, ${this.who}!`;

}

world.farewell(); // => 'Good bye, World!'


world object at first doesn't have a method farewell. It is added dynamically.

The dynamically added method can be invoked as a method without problems: world.farewell().

3. Class method

In JavaScript, the class syntax defines a class that's going to serve as a template for its instances.

A class can also have methods:


class Greeter {

constructor(who) {

this.who = who;

}

greet() {

console.log(this === myGreeter); // logs true

return `Hello, ${this.who}!`;

}

}

const myGreeter = new Greeter('World');

myGreeter.greet(); // => 'Hello, World!'


greet() { ... } is a method defined inside a class.

Every time you create an instance of the class using new operator (e.g. myGreeter = new Greeter('World')), methods are available for invocation on the created instance.

myGreeter.greet() is how you invoke the method greet() on the instance. What's important is that this inside of the method equals the instance itself: this equals myGreeter inside greet() { ... } method.

4. How to invoke a method

4.1 Method invocation

What's particularly interesting about JavaScript is that defining a method on an object or class is half of the job. To maintain the method the context, you have to make sure to invoke the method as a... method.

Let me show you why it's important.

Recall the world object having the method greet() upon it. Let's check what value has this when greet() is invoked as a method and as a regular function:


const world = {

who: 'World',

greet() {

console.log(this === world);

return `Hello, ${this.who}!`;

}

};

// Method invocation

world.greet(); // logs true

const greetFunc = world.greet;

// Regular function invocation

greetFunc(); // => logs false


world.greet() is a method invocation. The object world, followed by a dot ., and finally the method itself — that's what makes the method invocation.

greetFunc is the same function as world.greet. But when invoked as regular function greetFunc(), this inside greet() isn't equal to the world object, but rather to the global object (in a browser this is window).

I name expressions like greetFunc = world.greet separating a method from its object. When later invoking the separated method greetFunc() would make this equal to the global object.

Separating a method from its object can take different forms:


// Method is separated! this is lost!

const myMethodFunc = myObject.myMethod;

// Method is separated! this is lost!

setTimeout(myObject.myMethod, 1000);

// Method is separated! this is lost!

myButton.addEventListener('click', myObject.myMethod)

// Method is separated! this is lost!

<button onClick={myObject.myMethod}>My React Button</button>


To avoid loosing the context of the method, make sure to use the method invocation world.greet() or bind the method manually to the object greetFunc = world.greet.bind(this).

4.2 Indirect function invocation

As stated in the previous section, a regular function invocation has this resolved as the global object. Is there a way for a regular function to have a customizable value of this?

Welcome the indirect function invocation, which can be performed using:


myFunc.call(thisArg, arg1, arg2, ..., argN);

myFunc.apply(thisArg, [arg1, arg2, ..., argN]);


methods available on the function object.

The first argument of myFunc.call(thisArg) and myFunc.apply(thisArg) is the context (the value of this) of the indirect invocation. In other words, you can manually indicate what value this is going to have inside the function.

For example, let's define greet() as a regular function, and an object aliens having a who property:


function greet() {

return `Hello, ${this.who}!`;

}

const aliens = {

who: 'Aliens'

};

greet.call(aliens); // => 'Hello, Aliens!'

greet.apply(aliens); // => 'Hello, Aliens!'


greet.call(aliens) and greet.apply(aliens) are both indirect method invocations. this value inside the greet() function equals aliens object.

The indirect invocation lets you emulate the method invocation on an object!

4.3 Bound function invocation

Finally, here's the third way how you can make a function be invoked as a method on an object. Specifically, you can bound a function to have a specific context.

You can create a bound function using a special method:


const myBoundFunc = myFunc.bind(thisArg, arg1, arg2, ..., argN);


The first argument of myFunc.bind(thisArg) is the context to which the function is going to be bound to.

For example, let's reuse the greet() and bind it to aliens context:


function greet() {

return `Hello, ${this.who}!`;

}

const aliens = {

who: 'Aliens'

};

const greetAliens = greet.bind(aliens);

greetAliens(); // => 'Hello, Aliens!'


Calling greet.bind(aliens) creates a new function where this is bound to aliens object.

Later, when invoking the bound function greetAliens(), this equals aliens inside that function.

Again, using a bound function you can emulate the method invocation.

5. Arrow functions as methods

Using an arrow function as a method isn't recommended, and here's why.

Let's define the greet() method as an arrow function:


const world = {

who: 'World',

greet: () => {

return `Hello, ${this.who}!`;

}

};

world.greet(); // => 'Hello, undefined!'


Unfortunately, world.greet() returns 'Hello, undefined!' instead of the expected 'Hello, World!'.

The problem is that the value this inside of the arrow function equals this of the outer scope. Always. But what you want is this to equal world object.

That's why this inside of the arrow function equals the global object: window in a browser. 'Hello, ${this.who}!' evaluates as Hello, ${windows.who}!, which in the end is 'Hello, undefined!'.

I like the arrow functions. But they don't work as methods.

6. Summary

The method is a function belonging to an object. The context of a method (this value) equals the object the method belongs to.

You can also define methods on classes. this inside of a method of a class equals to the instance.

What's specific to JavaScript is that it is not enough to define a method. You also need to make sure to use a method invocation. Typically, the method invocation has the following syntax:


// Method invocation

myObject.myMethod('Arg 1', 'Arg 2');


Interestingly is that in JavaScript you can define a regular function, not belonging to an object, but then invoke that function as a method on an arbitrar object. You can do so using an indirect function invocation or bind a function to a particular context:


// Indirect function invocation

myRegularFunc.call(myObject, 'Arg 1', 'Arg 2');

myRegularFunc.apply(myObject, 'Arg 1', 'Arg 2');

// Bound function

const myBoundFunc = myRegularFunc.bind(myObject);

myBoundFunc('Arg 1', 'Arg 2');


Indirect invocation and bounding emulate the method invocation.

To read about all ways you can define functions in JavaScript follow my post JavaScript Function Declaration: The 6 Ways.

Confused about how this works in JavaScript? Then I recommend reading my extensive guide Gentle Explanation of "this" in JavaScript.

Quizzzzz: can a method in JavaScript be an asynchronous function?