While this works as intended
class ClassWithStaticMethod {
static staticMethod() {
return ('staticMethod');
};
static staticMethod2() {
const yee = this.staticMethod();
return 'staticMethod2 '+yee;
};
}
console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 staticMethod
This is,
i) have access to the staticMethod() with the class name, and
ii) this method can call another static method within the same class by using "this",
This doesn't work
class ClassWithStaticMethod {
static staticMethod = () => {
return ('staticMethod');
};
static staticMethod2 = () => {
const yee = this.staticMethod;
return 'staticMethod2 '+yee;
};
}
console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 undefined
In the sense, that I can still access to the staticMethod() method, but I am not able to access to the other method within the first method. I get undefined, and if I use
const yee = this.staticMethod();
I get an error
error TypeError: _this.staticMethod is not a function
Arrow functions inherit their this from the outer scope rather than their this depending on their calling context. Since staticMethod2 tries to access this.staticMethod, that will only work if this refers to ClassWithStaticMethod - that is, if staticMethod2 is a standard function, not an arrow function.
You also need to invoke this.staticMethod(). (const yee = this.staticMethod; will result in the staticMethod being coerced to a string, rather than being called)
Change those two issues, and it works as expected:
class ClassWithStaticMethod {
static staticMethod = () => {
return ('staticMethod');
};
static staticMethod2 = function() {
const yee = this.staticMethod();
return 'staticMethod2 '+yee;
};
}
console.log(ClassWithStaticMethod.staticMethod2());
That's one quirk with arrow functions when it comes to general use: they have generic scoping of this. (That's why we have to use function() if you want a better call stack). In the second method, this refers to the calling context: window.
As mentioned below in the comment, do not use the short-hand syntax for your convenience; there is a reason we have so many options.
To fix it, you can just use function() to define the second function; or () in the object case.
This, however, would work:
class ClassWithStaticMethod2 {
static staticMethod = () => {
return ('staticMethod');
};
static staticMethod2 = function() {
console.log(this)
const yee = this.staticMethod();
return 'staticMethod2 '+yee;
};
}
Check it out here.
Related
I am looking for a way to use something similar to Function.apply for classes so that the this property of an executed constructor is an external object.
With a function I can simply use apply
function Bar() {
this.value = 'value'
}
const proxy = {}
Bar.apply(proxy, [])
console.log(proxy) // { value: 'value' }
However this does not, of course, work with classes
class Foo {
constructor() {
this.value = 'value'
}
}
const proxy = {}
Foo.apply(proxy, [])
console.log(proxy)
Resulting in
Foo.apply(proxy, [])
^
TypeError: Class constructor Foo cannot be invoked without 'new'
Is it possible to bind the this context of a class constructor to another object?
I don't have any legacy clients so I am able to use Reflect.construct (though I am not sure if it can solve the problem)
EDIT:
Alternatively, I can work with replacing this after construction. Is that possible?
const foo = new Foo()
foo.bind(proxy)
If you have a look at [[Construct]] of function objects (which is the internal method which will be executed when you use new or Reflect.construct), then you'll find this step in the specification:
Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
As there is no way to change this behavior, you cannot change what thisArgument is, it is always a regular object and cannot be a proxy. However, if you use Reflect.construct, you can influence the newTarget, and pass something else in than the regular constructor:
class Constructed {} // this is the function object that will be [[Construct]]ed
class Trapped {} // the "thisArgument" will inherit Trapped.prototype
Reflect.construct(Constructed, [], Trapped);
By injecting a proxy into Trapped.prototype you can have some reflection onto this inside a class constructor. An example can be found here.
You could create a Proxy that traps the construct and returns a proxified instance to trap the mutations:
class Foo {
constructor() {
this.value = 'value';
}
}
const ProxifiedFoo = new Proxy(Foo, {
construct: (target, args) => {
const instance = new target(...args);
return new Proxy(instance, {
set: (_, prop, value) => console.log(`Trying to set ${prop} to ${value}`)
});
}
});
const foo = new ProxifiedFoo;
console.log('Current value:', foo.value);
foo.value = 'otherValue';
I have a code where a function is used to modify the existing functions and return a new function reference. I want that function to be applied to specific methods of a class.
My current code is
function modifyMethod(func) {
return function() {
console.log('working');
return func.apply(this, arguments);
};
}
function modifyClassMethods(ClassName, methodArray) {
// The code goes here
return ClassName;
}
class Temp {
hi() {
console.log("hi method");
}
}
Temp = modifyClassMethods(Temp, ["hi"]);
const temp = new Temp();
// This should print
//
// working
// hi method
temp.hi();
When I try to call the method modifyMethod with Temp.hi, func is undefined. If I create an object and then modify the method, then the new method will be applied only to the method of that particular object and not to all the objects of that particular class.
Note that this is just an example. I want to apply this modification to the methods of multiple classes. So, I can't generalize the method names also. Any code snippet for the modifyClassMethods will be helpful.
The methods defined with method syntax in the body of a class construct that aren't marked static are prototype methods and so they're on Temp.prototype, not Temp itself. So that's where you'd update them:
Temp.prototype.hi = modifyMethod(Temp.prototype.hi);
Only static methods end up on Temp itself.
You may see other functions created within the class body using the class fields proposal's syntax:
class Temp {
hi = () => {
//
};
}
Those are instance methods. They're created by the constructor, and re-created for each instance, roughly as though they'd been written like this:¹
class Temp {
constructor() {
this.hi = () => {
//
};
}
}
You can't wrap those until/unless an instance is created, as they're instance-specific.
So to wrap up, consider:
class Temp {
static staticMethod() {
// ...
}
prototypeMethod() {
// ...
}
instanceMethod = () => {
// ...
};
constructor() {
this.anotherInstanceMethod = () => {
// ...
};
this.yetAnotherInstanceMethod = function {
// ...
};
}
}
That class shows the three types of methods:
Static Methods, such as staticMethod, which you'll find on Temp (e.g., Temp.staticMethod);
Prototype Methods, such as prototypeMethod, which you'll find on Temp.prototype (e.g., Temp.prototype.prototypeMethod); and
Instance Methods, such as instanceMethod, anotherInstanceMethod, and yetAnotherInstanceMethod, which you'll find on the instances themselves, if/when any instances are created
¹ Technically, they're created as though with Object.defineProperty like this:
class Temp {
constructor() {
Object.defineProperty(this, "hi", {
value: () => {
//
},
writable: true,
configurable: true,
enumerable: true
});
}
}
...not via simple assignment. I used simple assignment in the example to keep it...simple. :-)
The below code snippet I found on one blogs to avoid if-else statement. This code is very modular and can be easily extended. But I am not able to get this to work.
CatModel.prototype.makeWords = function () {
console.log('inside catmodel')
this.setWord('meow')
this.sayIt()
}
DogModel.prototype.makeWords = function () {
console.log('inside dogmodel')
this.setWord('bark')
this.saySomething()
}
// somewhere else
var makeWords = function (type) {
var model = namespace[type + 'Model']
model.makeWords()
}
makeWords('cat')
Presumably the CatModel and DogModel functions are declared somewhere and setWord and sayIt are also set up on their prototype object.
You'd need to put CatModel and DogModel in an object and refer to it from namespace (which I'd recommend not calling namespace):
var namespace = {
CatModel: CatModel,
DogModel: DogModel
};
Then when creating an instance, use new (you always use new with constructor functions). I'd also put the () on the call even though strictly speaking they're optional if you don't have parameters to pass:
var makeWords = function (type) {
var model = new namespace[type + 'Model']()
// ---------^^^--------------------------^^
model.makeWords()
}
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. :)
I'm new to JavaScript. New as far as all I've really done with it is tweaked existing code and wrote small bits of jQuery.
Now I'm attempting to write a "class" with attributes and methods, but I'm having trouble with the methods. My code:
function Request(destination, stay_open) {
this.state = "ready";
this.xhr = null;
this.destination = destination;
this.stay_open = stay_open;
this.open = function(data) {
this.xhr = $.ajax({
url: destination,
success: this.handle_response,
error: this.handle_failure,
timeout: 100000000,
data: data,
dataType: 'json',
});
};
/* snip... */
}
Request.prototype.start = function() {
if( this.stay_open == true ) {
this.open({msg: 'listen'});
} else {
}
};
//all console.log's omitted
The problem is, in Request.prototype.start, this is undefined and thus the if statement evaluates to false. What am I doing wrong here?
I just wanted to point out that sometimes this error happens because a function has been used as a high order function (passed as an argument) and then the scope of this got lost. In such cases, I would recommend passing such function bound to this. E.g.
this.myFunction.bind(this);
How are you calling the start function?
This should work (new is the key)
var o = new Request(destination, stay_open);
o.start();
If you directly call it like Request.prototype.start(), this will refer to the global context (window in browsers).
Also, if this is undefined, it results in an error. The if expression does not evaluate to false.
Update: this object is not set based on declaration, but by invocation. What it means is that if you assign the function property to a variable like x = o.start and call x(), this inside start no longer refers to o. This is what happens when you do setTimeout. To make it work, do this instead:
var o = new Request(...);
setTimeout(function() { o.start(); }, 1000);
None of the previous answers had the full solution for me, so posting mine here.
I had a class, which was returning an error when I ran forEach on the method reference.
e.g.
class Foo {
hello (name) {
return `hello ${name}`
}
doGreet (name) {
return console.log(this.hello(name)) // <- 'this' is undefined
}
}
// print some names...
const foo = new Foo();
(['nick', 'john']).forEach(foo.doGreet)
// TypeError: Cannot read property 'hello' of undefined
// at doGreet (/.../test.js:7:17)
The solution was to the bind the context of the method's this within a constructor. i.e.
class Foo {
constructor () {
this.doGreet = this.doGreet.bind(this) // <- Add this
}
hello (name) {
return `hello ${name}`
}
doGreet (name) {
return console.log(this.hello(name))
}
}
JavaScript's OOP is a little funky (or a lot) and it takes some getting used to. This first thing you need to keep in mind is that there are no Classes and thinking in terms of classes can trip you up. And in order to use a method attached to a Constructor (the JavaScript equivalent of a Class definition) you need to instantiate your object. For example:
Ninja = function (name) {
this.name = name;
};
aNinja = new Ninja('foxy');
aNinja.name; //-> 'foxy'
enemyNinja = new Ninja('boggis');
enemyNinja.name; //=> 'boggis'
Note that Ninja instances have the same properties but aNinja cannot access the properties of enemyNinja. (This part should be really easy/straightforward) Things get a bit different when you start adding stuff to the prototype:
Ninja.prototype.jump = function () {
return this.name + ' jumped!';
};
Ninja.prototype.jump(); //-> Error.
aNinja.jump(); //-> 'foxy jumped!'
enemyNinja.jump(); //-> 'boggis jumped!'
Calling this directly will throw an error because this only points to the correct object (your "Class") when the Constructor is instantiated (otherwise it points to the global object, window in a browser)
Use arrow function:
Request.prototype.start = () => {
if( this.stay_open == true ) {
this.open({msg: 'listen'});
} else {
}
};
In ES2015 a.k.a ES6, class is a syntactic sugar for functions.
If you want to force to set a context for this you can use bind() method. As #chetan pointed, on invocation you can set the context as well! Check the example below:
class Form extends React.Component {
constructor() {
super();
}
handleChange(e) {
switch (e.target.id) {
case 'owner':
this.setState({owner: e.target.value});
break;
default:
}
}
render() {
return (
<form onSubmit={this.handleNewCodeBlock}>
<p>Owner:</p> <input onChange={this.handleChange.bind(this)} />
</form>
);
}
}
Here we forced the context inside handleChange() to Form.
This question has been answered, but maybe this might someone else coming here.
I also had an issue where this is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:
import MyClass from "./myClass"
// 'this' is not defined here:
const { aMethod } = new MyClass()
aMethod() // error: 'this' is not defined
// So instead, init as you would normally:
const myClass = new MyClass()
myClass.aMethod() // OK
If a function has been used as a high order function (passed as an argument) the scope of this gets lost.
To fix this problem one can bind this to the function like #Eliux described:
this.myFunction.bind(this);
To automate this process like #DanielTonon wanted you can do this in the constructor:
Object.getOwnPropertyNames(YourClass.prototype).forEach((key) => {
if (key !== 'constructor') {
this[key] = this[key].bind(this);
}
});
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42