by
81k 39
18
9
6.9M
315
Top 1% !
Popular
Famous
Pearl of Wisdom
Tagged
Easy-to-find
Specified
Debate
OpenSource
Popularity: 25th place
Created
Modified Mar 4, 2014

Published on:

Frameworknode.js
Languagetypescript
libraryunderscore
LicenseMIT_X11

Related

Typescript: passing a class member function as parameter to another function

Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost.

To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expression) to preserve the instance for the function you want to pass as argument.

The example in this snippet runs on node.js  with typescript 0.9.5
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/28601/Typescript--passing-a-class-member-funct?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
///<reference path='../types/node.d.ts'/> ///<reference path='../types/underscore.d.ts'/> import _ = require("underscore"); class SomePeople { values : string[] = [ 'John', 'Mary', 'Peter']; out() { _.each( this.values, (v) => process.stdout.write( v + '\n') ); } } // This function accept a function it will execute internally function outSomething( outFunc : () => any ) { outFunc(); } var crowd = new SomePeople(); // This won't work since the actual crowd instance binding will be lost outSomething( crowd.out ); // This will work: the closure within the lambda expression retain the // crowd instance and its data outSomething( () => crowd.out() );
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus