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

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
this in JavaScript and TypeScript
2020-08-19 · via oida.dev | TypeScript, Rust

Sometimes when writing JavaScript, I want to shout “This is ridiculous!”. But then I never know what this refers to.

If there is one concept in JavaScript that confuses people, it has to be this. Especially if your background is a class-based object-oriented programming languages, where this always refers to an instance of a class. this in JavaScript is entirely different, but not necessarily harder to understand. There’re a few basic rules, and about as many exceptions to keep in mind. And TypeScript can help greatly!

this in regular JavaScript functions #

A way I like to think about this is that in regular functions (with the function keyword or the object function short-hand), resolve to “the nearest object”, which is the object that they are bound to. For example:

const author = {
name: "Stefan",
// function shorthand
hi() {
console.log(this.name);
},
};

author.hi(); // prints 'Stefan'

In the example above, hi is bound to author, so this is author.

JavaScript is flexible, you can attach functions or apply functions to an object on the fly.

const author = {
name: "Stefan",
// function shorthand
hi() {
console.log(this.name);
},
};

author.hi(); // prints 'Stefan'

const pet = {
name: "Finni",
kind: "Cat",
};

pet.hi = author.hi;

pet.hi(); // prints 'Finni'

The “nearest object” is pet. hi is bound to pet.

We can declare a function independently from objects and still use it in the object context with apply or call:

function hi() {
console.log(this.name);
}

const author = {
name: "Stefan",
};

const pet = {
name: "Finni",
kind: "Cat",
};

hi.apply(pet); // prints 'Finni'
hi.call(author); // prints 'Stefan'

The nearest object is the object we pass as the first argument. The documentation calls the first argument thisArg, so the name tells you already what to expect.

apply vs call #

What’s the difference between call and apply? Think of a function with arguments:

function sum(a, b) {
return a + b;
}

With call you can pass the arguments one by one:

sum.call(null, 2, 3);

null is the object sum should be bound to, so no object.

With apply, you have to pass the arguments in an array:

sum.apply(null, [2, 3]);

An easy mnemonic to remember this behaviour is array for apply, commas for call.

bind #

Another way to explicitly bind an object to an object-free function is by using bind

const author = {
name: "Stefan",
};

function hi() {
console.log(this.name);
}

const boundHi = hi.bind(author);

boundHi(); // prints 'Stefan'

This is already cool, but more on that later.

Event listeners #

The concept of the “nearest object” helps a lot when you work with event listeners:

const button = document.querySelector("button");

button.addEventListener("click", function () {
this.classList.toggle("clicked");
});

this is button. addEventListener sets one of many onclick functions. Another way of doing that would be

button.onclick = function () {
this.classList.toggle("clicked");
};

which makes it a bit more obvious why this is button in that case.

this in arrow functions and classes #

So I spent half of my professional JavaScript career to totally understand what this refers to, just to see the rise of classes and arrow functions that turn everything upside down again.

Here's my most favorite meme on this (click to expand)
Two people shouting at each other: This is the difference between arrow functions and normal functions. What is the difference? This is the difference? And so on, and so on.
My most favourite this meme

Arrow functions always resolve this respective to their lexical scope. Lexical scope means that the inner scope is the same as the outer scope, so this inside an arrow function is the same as outside an arrow function. For example:

const lottery = {
numbers: [4, 8, 15, 16, 23, 42],
el: "span",
html() {
// this is lottery
return this.numbers
.map(
(number) =>
//this is still lottery
`<${this.el}>${number}</${this.el}>`
)
.join();
},
};

Calling lottery.html() gets us a string with all numbers wrapped in spans, as this inside the arrow function of map doesn’t change. It’s still lottery.

If we would use a regular function, this would be undefined, as there is no nearest object. We would have to bind this:

const lottery = {
numbers: [4, 8, 15, 16, 23, 42],
el: "span",
html() {
// this is lottery
return this.numbers
.map(
function (number) {
return `<${this.el}>${number}</${this.el}>`;
}.bind(this)
)
.join("");
},
};

Tedious.

In classes, this also refers to the lexical scope, which is the class instance. Now we’re getting Java-y!

class Author {
constructor(name) {
this.name = name;
}

// lexical, so Author
hi() {
console.log(this.name);
}

hiMsg(msg) {
// lexical, so still author!
return () => {
console.log(`${msg}, ${this.name}`);
};
}
}

const author = new Author("Stefan");
author.hi(); //prints '
author.hiMsg("Hello")(); // prints 'Hello, Stefan'

unbinding #

Problems occur if you accidentally unbind a function, e.g. by passing a function that is bound to some other function or storing it in a variable.

const author = {
name: "Stefan",
hi() {
console.log(this.name);
},
};

const hi = author.hi();
// hi is unbound, this refers to nothing
// or window/global in non-strict mode
hi(); // 💥

You would have to re-bind the function. This also explains some behaviour in React class components with event handlers:

class Counter extends React.Component {
constructor() {
super();
this.state = {
count: 1,
};
}

// we have to bind this.handleClick to the
// instance again, because after being
// assigned, the function loses its binding ...
render() {
return (
<>
{this.state.count}
<button onClick={this.handleClick.bind(this)}>+</button>
</>
);
}

//... which would error here as we can't
// call `this.setState`
handleClick() {
this.setState(({ count }) => ({
count: count + 1,
}));
}
}

this in TypeScript #

TypeScript is pretty good at finding the “nearest object” or knowing the lexical scope, so TypeScript can give you exact information on what to expect from this. There are however some edge cases where we can help a little.

this arguments #

Think of extract an event handler function into its own function:

const button = document.querySelector("button");
button.addEventListener("click", handleToggle);

// Huh? What's this?
function handleToggle() {
this.classList.toggle("clicked"); //💥
}

We lose all information on this since this would now be window or undefined. TypeScript gives us red squigglies as well!

We add an argument at the first position of the function, where we can define the type of this.

const button = document.querySelector("button");
button.addEventListener("click", handleToggle);

function handleToggle(this: HTMLElement) {
this.classList.toggle("clicked"); // 😃
}

This argument gets removed once compiled. We now know that this will be of type HTMLElement, which also means that we get errors once we use handleToggle in a different context.

// The 'this' context of type 'void' is not
// assignable to method's 'this' of type 'HTMLElement'.
handleToggle(); // 💥

ThisParameterType and OmitThisParameter #

There are some helpers if you use this parameters in your function signatures.

ThisParameterType tells you which type you expect this to be:

const button = document.querySelector("button");
button.addEventListener("click", handleToggle);

function handleToggle(this: HTMLElement) {
this.classList.toggle("clicked"); // 😃
handleClick.call(this);
}

function handleClick(this: ThisParameterType<typeof handleToggle>) {
this.classList.add("clicked-once");
}

OmitThisParameter removes the this typing and gives you the blank type signature of a function.

// No reason to type `this` here!
function handleToggle(this: HTMLElement) {
console.log("clicked!");
}

type HandleToggleFn = OmitThisParameter<typeof handleToggle>;

declare function toggle(callback: HandleToggleFn);

toggle(function () {
console.log("Yeah works too");
}); // 👍

ThisType #

There’s another generic helper type that helps defining this for objects called ThisType. It originally comes from the way e.g. Vue handles objects. For example:

var app5 = new Vue({
el: "#app-5",
data: {
message: "Hello Vue.js!",
},
methods: {
reverseMessage() {
// OK, so what's this?
this.message = this.message.split("").reverse().join("");
},
},
});

Look at this in the reverseMessage() function. As we learned, this refers to the nearest object, which would be methods. But Vue transforms this object into something different, so you can access all elements in data and all methods in methods (eg. this.reverseMessage()).

With ThisType we can declare the type of this at this particular position.

The Object descriptor for the code above would look like this:

type ObjectDescriptor<Data, Methods> = {
el?: string;
data?: Data;
methods?: Methods & ThisType<Data & Methods>;
};

It tells TypeScript that within all functions of methods, this can access to fields from type Data and Methods.

Typing this minimalistic version of Vue looks like that:

declare const Vue: VueConstructor;

type VueConstructor = {
new<D, M>(desc: ObjectDescriptor<D, M>): D & M
)

ThisType<T> in lib.es5.d.ts itself is empty. It’s a marker for the compiler to point this to another object. As you can see in this playground, this is exactly what it should be.

Bottom line #

I hope this piece on this did shed some light on the different quirks in JavaScript and how to type this in TypeScript. If you have any questions, feel free to reach out to me.

Related Articles