Referenz im Objektliteral
bearbeitet von Christian KruseHallo dedlfix,
> Ahh, habs rausgefunden, mithilfe des [TypeScript-Playgrounds](https://www.typescriptlang.org/play/).
>
> ~~~JavaScript
> let myObject = {
> foo: () => { console.log(this.array2); }
> };
> ~~~
>
> wird dort übersetzt zu
>
> ~~~JavaScript
> var _this = this;
> var myObject = {
> foo: function () { console.log(_this.array2); }
> };
> ~~~
>
> Und da erinnerte ich mich, dass bei den Fat-Arrow-Funktionen `() => {}` das Typescript das this auf den äußeren Kontext legt. ["... the ECMAScript 6 arrow syntax. Arrow functions capture the `this` where the function is created rather than where it is invoked"](https://www.typescriptlang.org/docs/handbook/functions.html#this-and-arrow-functions)
Das wollte ich dir gerade auch schreiben 😉
> Eine herkömmliche anonymous-function-Notation löst das `this` erst zur Laufzeit auf. Wenn du dein Objekt so erstellst
>
> ~~~JavaScript
> let myObject = {
> array1: [1, 2, 3],
>
> foo: function() { console.log(this.array2); }
> };
> ~~~
In ES2015 kannst du auch folgendes schreiben:
~~~js
let myObject = {
array1: [1, 2, 3],
foo() { console.log(this.array2); }
};
myObject.array2 = myObject.array1.map(x => x + 1);
myObject.foo()
~~~
[Siehe auch: method definitions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions)
LG,
CK
--
<https://wwwtech.de/about>