I have 2 classes, one of them is a general utility class used by the entire application. I would like to reference the this property of the caller class in the callee utility class.
I am unsure what the best practice for this is.
I have provided an example of what I'm trying to do.
I one case I can use .call to provide the correct this context or I can pass this in as a function parameter.
class Caller {
doSomething() {
Utility.calledMethod.call(this, 'paramStr');
Utility.calledMethodWithThis(this, 'paramStr');
}
doAnotherThing(param) {
console.log(param);
}
}
// Shared Class of utility methods used for entire application
class Utility {
static calledMethod(param) {
this.doAnotherThing(param);
}
static calledMethodWithThis(self, param) {
self.doAnotherThing(param);
}
}
const caller = new Caller();
caller.doSomething();
https://jsfiddle.net/pvafedho/
This looks like a scenario where you can utilize a mixin.
Following the example from this page: https://javascript.info/mixins
Your code could look like this:
// Shared Class of utility methods used for entire application
let utilityMixin = {
calledMethod(param) {
this.doAnotherThing(param);
}
}
class Caller {
constructor() {
this.mystring = 'hello!'
}
doSomething() {
this.calledMethod(this.mystring);
}
doAnotherThing(param) {
console.log(param);
}
}
Object.assign(Caller.prototype, utilityMixin );
const caller = new Caller();
caller.doSomething();
Related
In python there's something like __call__ for this. Consider the following example:
class MyClass {
__call__() { return 'called!' }
}
const myType = new MyClass();
myType(); // called!
The question is what should I replace __call__ with?
I was doing some research, and most of the answers recommend __proto__, but it doesn't seem to work.
It is not possible out-of-the-box, but you can extend Function, and use the Function constructor to forward a call to __call__. If you have multiple classes that need this feature, extend Function only once into -- let's say -- a Callable class, and then inherit your other classes from that:
class Callable extends Function {
constructor() {
super("...args", "return this.__call__(...args)");
return this.bind(this);
}
}
class Class extends Callable {
__call__() { return 'called!' }
}
let inst = new Class();
console.log(inst());
Background
In JavaScript an object is callable when, and only if, it has the [[Call]] internal slot. But there is (currently) no way to give any given object this slot via JavaScript code. One must start with a function object and extend that.
Adding a constructor, inheritance
The above solution allows the constructor to define properties in the usual way: the constructed object is an instance of the class:
class Callable extends Function {
constructor() {
super("...args", "return this.__call__(...args)");
return this.bind(this);
}
}
class Class extends Callable {
constructor(data) {
super();
this.x = data;
}
__call__() { return 'called!' }
}
let inst = new Class(42);
console.log(inst instanceof Class); // true
console.log(inst.x); // 42
console.log(inst());
You can use constructor.
class Example {
constructor() {
// gets called on class initialization
}
}
Inside the constructor you can also call other methods if you want.
However this won't create an invoke function like using PHP's __invoke if that's what you meant. If that's what you're looking for then I don't know.
Let's say I have a program:
class Program {
constructor() {
this.profileManager = new ProfileManager();
}
saveProgramConfig() {
// ...
}
}
If something happens inside ProfileManager, and it needs to save the program configuration, what would be the best way of accessing this specific instance's saveProgramConfig method from inside the ProfileManager class?
You could pass the instance as an argument so that both instances have a link to each other:
this.profileManager = new ProfileManager(this);
and have ProfileManager save the instance to one of its own properties, and call saveProgramConfig on it when needed.
What the issue with the following approach? you can access the test method of Program inside ProfileManager class.
class Program {
test() {
return "Hello World";
}
}
class ProfileManager extends Program {
constructor() {
super();
}
main() {
return this.test();
}
}
const tp = new B;
console.log(tp.main());
I am using a parent class in my app to provide some basic functionality to its children. It looks roughly like this:
class Base {
constructor(stream) {
stream.subscribe(this.onData)
}
onData(data) {
throw new Error('"onData" method must be implemented')
}
}
class Child extends Base {
onData(data) {
// do stuff...
}
}
That works fine and when I instantiate the Child, Base passes Child.onData to the stream
The only problem is scope. In Child.onData I make a heavy use of other methods defined in child via this keyword. So when I pass this function as a callback to the stream, everything breaks. The evident solution is this:
class Base {
constructor(stream) {
stream.subscribe(this.onData)
}
onData = (data) => {
throw new Error('"onData" method must be implemented')
}
}
class Child extends Base {
onData = (data) => {
// do stuff...
}
}
That does solve problems with scope, but now the function that is being passed to the stream is always Base.onData which throws errors. Generally, I could do something like passing the Child.onData to Base constructor. That would work, but what I would like to find is a more elegant solution to this, if it exists
That's why arrow functions in class properties are not that great. If you translate it to a normal ES6 class, this is what happens:
class Child extends Base {
constructor(...args) {
super(...args);
this.onData = (data) => {
// do stuff...
};
}
}
It's rather evident now why using the property inside the Base constructor doesn't work.
Instead, you should use normal method definitions and handle the context problem by binding the method inside the parent constructor:
class Base {
constructor(stream) {
if (this.onData == Base.prototype.onData)
throw new Error('"onData" method must be overridden')
this.onData = this.onData.bind(this);
stream.subscribe(this.onData)
}
onData(data) {}
}
class Child extends Base {
onData(data) {
// do stuff...
}
}
I've implemented a library that exposes a function speach() to create an object with specific public API functions. The functions proxy to an internal object class Speach which I don't expose to the end-user so the implementation details cannot be touched. I can change implementation details later as long as I continue to support the publicly exposed API.
Is there a name for this pattern?
class Speach {
constructor() {
// ...
}
browserSupportsFeature() {}
loadAPI() {}
voice(name) {
// ...
}
speak(textToSpeak) {
// ...
}
then(onFulfilled, onRejected) {
// ...
}
}
const speach = () => {
const speach = new Speach();
return {
voice(name) {
speach.voice(name);
return this;
},
speak(textToSpeak) {
speach.speak(textToSpeak);
return this;
},
then(thenable) {
speach.then(thenable);
return this;
}
};
};
Abstraction.
Abstraction is when you hide implementation details and only expose the interface to the client. The developer can change the underlying implementation as they please as long as the outside interface stays the same.
Restricting access to variables by limiting their scope inside a closure is called information hiding.
This implementation is basically the the Module pattern.
I have a TypeScript class, with a function that I intend to use as a callback:
removeRow(_this:MyClass): void {
...
// 'this' is now the window object
// I must use '_this' to get the class itself
...
}
I pass it in to another function
this.deleteRow(this.removeRow);
which in turn calls a jQuery Ajax method, which if successful, invokes the callback like this:
deleteItem(removeRowCallback: (_this:MyClass) => void ): void {
$.ajax(action, {
data: { "id": id },
type: "POST"
})
.done(() => {
removeRowCallback(this);
})
.fail(() => {
alert("There was an error!");
});
}
The only way I can preserve the 'this' reference to my class is to pass it on to the callback, as demonstrated above. It works, but it's pants code. If I don't wire up the 'this' like this (sorry), then any reference to this in the callback method has reverted to the Window object. Because I'm using arrow functions all the way, I expected that the 'this' would be the class itself, as it is elsewhere in my class.
Anyone know how to pass callbacks around in TypeScript, preserving lexical scope?
Edit 2014-01-28:
New readers, make sure you check out Zac's answer below.
He has a much neater solution that will let you define and instantiate a scoped function in the class definition using the fat arrow syntax.
The only thing I will add is that, in regard to option 5 in Zac's answer, it's possible to specify the method signature and return type without any repetition using this syntax:
public myMethod = (prop1: number): string => {
return 'asdf';
}
Edit 2013-05-28:
The syntax for defining a function property type has changed (since TypeScript version 0.8).
Previously you would define a function type like this:
class Test {
removeRow: (): void;
}
This has now changed to:
class Test {
removeRow: () => void;
}
I have updated my answer below to include this new change.
As a further aside: If you need to define multiple function signatures for the same function name (e.g. runtime function overloading) then you can use the object map notation (this is used extensively in the jQuery descriptor file):
class Test {
removeRow: {
(): void;
(param: string): string;
};
}
You need to define the signature for removeRow() as a property on your class but assign the implementation in the constructor.
There are a few different ways you can do this.
Option 1
class Test {
// Define the method signature here.
removeRow: () => void;
constructor (){
// Implement the method using the fat arrow syntax.
this.removeRow = () => {
// Perform your logic to remove the row.
// Reference `this` as needed.
}
}
}
If you want to keep your constructor minimal then you can just keep the removeRow method in the class definition and just assign a proxy function in the constructor:
Option 2
class Test {
// Again, define the method signature here.
removeRowProxy: () => void;
constructor (){
// Assign the method implementation here.
this.removeRowProxy = () => {
this.removeRow.apply(this, arguments);
}
}
removeRow(): void {
// ... removeRow logic here.
}
}
Option 3
And finally, if you're using a library like underscore or jQuery then you can just use their utility method to create the proxy:
class Test {
// Define the method signature here.
removeRowProxy: () => void;
constructor (){
// Use jQuery to bind removeRow to this instance.
this.removeRowProxy = $.proxy(this.removeRow, this);
}
removeRow(): void {
// ... removeRow logic here.
}
}
Then you can tidy up your deleteItem method a bit:
// Specify `Function` as the callback type.
// NOTE: You can define a specific signature if needed.
deleteItem(removeRowCallback: Function ): void {
$.ajax(action, {
data: { "id": id },
type: "POST"
})
// Pass the callback here.
//
// You don't need the fat arrow syntax here
// because the callback has already been bound
// to the correct scope.
.done(removeRowCallback)
.fail(() => {
alert("There was an error!");
});
}
UPDATE: See Sly's updated answer. It incorporates an improved version of the options below.
ANOTHER UPDATE: Generics
Sometimes you want to specify a generic type in a function signature without having to specify it on the the whole class. It took me a few tries to figure out the syntax, so I thought it might be worth sharing:
class MyClass { //no type parameter necessary here
public myGenericMethod = <T>(someArg:string): QPromise<T> => {
//implementation here...
}
}
Option 4
Here are a couple more syntaxes to add to Sly_cardinal's answer. These examples keep the function declaration and implementation in the same place:
class Test {
// Define the method signature AND IMPLEMENTATION here.
public removeRow: () => void = () => {
// Perform your logic to remove the row.
// Reference `this` as needed.
}
constructor (){
}
}
or
Option 5
A little more compact, but gives up explicit return type (the compiler should infer the return type anyway if not explicit):
class Test {
// Define implementation with implicit signature and correct lexical scope.
public removeRow = () => {
// Perform your logic to remove the row.
// Reference `this` as needed.
}
constructor (){
}
}
Use .bind() to preserve context within the callback.
Working code example:
window.addEventListener(
"resize",
(()=>{this.retrieveDimensionsFromElement();}).bind(this)
)
The code in original question would become something like this:
$.ajax(action, {
data: { "id": id },
type: "POST"
})
.done(
(() => {
removeRowCallback();
}).bind(this)
)
It will set the context (this) inside the callback function to whatever was passed as an argument to bind function, in this case the original this object.
This is sort of a cross post from another answer (Is there an alias for 'this' in TypeScript?). I re-applied the concept using the examples from above. I like it better than the options above because it explictly supports "this" scoping to both the class instance as well as the dynamic context entity that calls the method.
There are two versions below. I like the first one because the compiler assists in using it correctly (you won't as easily try to misuse the callback lambda itself as the callback, because of the explicitly typed parameter).
Test it out:
http://www.typescriptlang.org/Playground/
class Test {
private testString: string = "Fancy this!";
// Define the method signature here.
removeRowLambdaCallback(outerThis: Test): {(): void} {
alert("Defining callback for consumption");
return function(){
alert(outerThis.testString); // lexically scoped class instance
alert(this); // dynamically scoped context caller
// Put logic here for removing rows. Can refer to class
// instance as well as "this" passed by a library such as JQuery or D3.
}
}
// This approach looks nicer, but is more dangerous
// because someone might use this method itself, rather
// than the return value, as a callback.
anotherRemoveRowLambdaCallback(): {(): void} {
var outerThis = this;
alert("Defining another callback for consumption");
return function(){
alert(outerThis.testString); // lexically scoped class instance
alert(this); // dynamically scoped context caller
// Put logic here for removing rows. Can refer to class
// instance as well as "this" passed by a library such as JQuery or D3.
}
}
}
var t = new Test();
var callback1 = t.removeRowLambdaCallback(t);
var callback2 = t.anotherRemoveRowLambdaCallback();
callback1();
callback2();
Building upon sly and Zac's answers with types:
A complete hello world example. I hope this is welcome, seeing as this is the top result in Google, when searching for "typescript javascript callbacks"
type MyCallback = () => string;
class HelloWorld {
// The callback
public callback: MyCallback = () => {
return 'world';
}
// The caller
public caller(callback: MyCallback) {
alert('Hello ' + callback());
}
}
let hello = new HelloWorld();
hello.caller(hello.callback);
This gets transpiled into:
var HelloWorld = (function () {
function HelloWorld() {
// The callback
this.callback = function () {
return 'world';
};
}
// The caller
HelloWorld.prototype.caller = function (callback) {
alert('Hello ' + callback());
};
return HelloWorld;
}());
var hello = new HelloWorld();
hello.caller(hello.callback);
Hope someone finds it just a little useful. :)