This project is read-only.

this, this and this

Topics: Language Specification
Sep 27, 2013 at 7:17 AM
Hi guys,

Is there a way to access javascript's this within lambda?
Sep 27, 2013 at 4:13 PM
I assume you're asking because this:
    var fxn = () => {
        this.a = "a";
transpiles to this:
    var _this = this;
    var fxn = function () {
        _this.a = "a";
and you want access to the original this inside that function.

I wouldn't expect to be able to do that because that's an implementation detail. Were your TypeScript to compile to EcmaScript 6 then it would use the native fat arrow where this is this and there is no other concept of this.
Sep 27, 2013 at 4:27 PM
Edited Sep 27, 2013 at 4:27 PM
Yep, sometimes one needs both. They could introduce a new keyword: realThis :)
Sep 27, 2013 at 10:58 PM
I often find myself needing both the traditional JavaScript this and the lexicographical this. Would be great if we could use "<this>" or something inside lambdas to reference the traditional this.

With current TypeScript output, it could simply not rewrite it as "_this". With ES6, it'd have to basically do what it does with the current this in lambdas.

Right now my only option seems to be to drop lamda syntax entirely in these cases and setup a "self" variable myself. Which is kind of awkward and leads to inconsistent code.
Sep 29, 2013 at 11:27 AM
The "traditional" this can be referenced by defining a function instead of a lambda.
var button = document.createElement("button");
button.innerHTML = "Foo";

button.onclick = function() {
    alert(this.innerHTML); // Alerts "foo"
Sep 29, 2013 at 11:29 AM
Sure, no problems there, but then you have to store the other this if you want to use it. It'd be nice to have both without additional code.
Sep 29, 2013 at 6:19 PM
The other "this" in my example is button. Not sure I understand. Would you care to elaborate with an example?

Just curious because I haven't yet found myself thinking there was some missing functionality here.