The premise of this question, How to translate 'this' in D3 JavaScript to TypeScript?, is false. I did not downvote because it is important to educate.
I just want to clarify that this
is 100% identical in TypeScript and JavaScript
In fact, all TypeScript syntax that is also valid JavaScript syntax has the exact same semantics.
This is what makes TypeScript a superset of JavaScript.
Update: I actually will amend this with an answer because the problem was that you thought the meaning was different. You are confused about arrow function syntax
(params) => expression or block
First of all =>
is not a TypeScript feature, but a JavaScript feature.
Secondly, TypeScript, as noted above naturally support both forms. This means that no translation is needed.
this
means the same thing in TypeScript as it does in JavaScript.
In both languages it means something different in the context of =>
than it does in the context of function
. There are many, many answers explaining this on SO, so I won't repeat them.
So here is the answer to this question.
If you have this file:
d3-app.js
node.on('click', function (d) {
d3.selectAll('circle').attr('stroke-width', 1.5);
d3.select(this).select('circle').attr('stroke-width', 5);
});
It works and you want to rewrite it in TypeScript.
Here is what you do:
- rename d3-app.js to d3-app.ts
That is all.
this
has absolutely the same meaning an behavior in TS and JS. Would be interesting to see more code. It's strange that you usethis.node
as a replacement ford3
and fornode
simultaneously. Is it correct in your case? – dfsq Apr 21 '17 at 19:32this
behaves differently from other languages. – artem Apr 21 '17 at 19:36d
object (the first argument). However, the second and third arguments can be easily used to getthis
(which in D3 methods is the current DOM element). – Gerardo Furtado Apr 22 '17 at 9:31