Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want <code>this</code> captured the TypeScript way of doing this is via arrow functions. To quote Anders:</p> <blockquote> <p>The <code>this</code> in arrow functions is lexically scoped</p> </blockquote> <p>Here is the way I like to use this to my advantage:</p> <pre><code>class test{ // Use arrow functions func1=(arg:string)=&gt;{ return arg+" yeah" + this.prop; } func2=(arg:number)=&gt;{ return arg+10 + this.prop; } // some property on this prop = 10; } </code></pre> <p><a href="http://www.typescriptlang.org/Playground/#src=class%20test%7B%0A%09%2F%2F%20Use%20arrow%20functions%0A%09func1%3D(arg%3Astring)%3D%3E%7B%0A%09%09%09return%20arg%2B%22%20yeah%22%20%2B%20this.prop%3B%0A%09%7D%0A%09func2%3D(arg%3Anumber)%3D%3E%7B%0A%09%09%09return%20arg%2B10%20%2B%20this.prop%3B%0A%09%7D%09%09%0A%09%09%0A%09%2F%2F%20some%20property%20on%20this%0A%09prop%20%3D%2010%3B%0A%7D" rel="noreferrer">View this in the TypeScript Playground</a></p> <p>You can see that in the generated JavaScript <code>this</code> is captured <em>outside</em> the function call:</p> <pre><code>var _this = this; this.prop = 10; this.func1 = function (arg) { return arg + " yeah" + _this.prop; }; </code></pre> <p>so the <code>this</code> value inside the function call (which could be <code>window</code>) would not be used.</p> <p>To learn more: <a href="https://www.youtube.com/watch?v=tvocUcbCupA&amp;hd=1" rel="noreferrer">“Understanding <code>this</code> in TypeScript” (4:05) – YouTube</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload