Callable class instances
# Raul-Sebastian Mihăilă (9 years ago)
It seems to me that you are mixing Foo and f. If that's not intended then what you want can be obtained with:
var x = 0;
function Foo() {
if (new.target) {
this.i = 0;
} else {
// I don't know what class.instance is supposed to mean.
return x++;
}
}
Object.setPrototypeOf(Foo, null);
All the functions that we create are user defined callable objects.
# Raul-Sebastian Mihăilă (9 years ago)
Forgot about instanceof.
var x = 0;
function Foo() {
if (new.target) {
this.i = 0;
} else {
// I don't know what class.instance is supposed to mean.
return x++;
}
}
Object.setPrototypeOf(Foo, null);
Foo[Symbol.hasInstance] = () => false;
# Claude Pache (9 years ago)
Le 3 mars 2016 à 18:04, Michał Wadas <michalwadas at gmail.com> a écrit :
Are there any plans/proposals to specify user defined callable objects?
It's possible to extend Function, but it requires to specify function code as string and prevents usage of local variables.
Eg:
class Foo { constructor() { this.i=0; } [Symbol.call]() { return class.instance.i++; // new meta property } } const f = new Foo; typeof f === 'function'; f instanceof Function === false; // most use cases would be Function instances f() === 0; f() === 1; f.call(null); // TypeError: undefined is not a function
The following code should work (it did for me in Chrome):
class Foo {
constructor() {
let obj = () => obj.i++;
Object.setPrototypeOf(obj, new.target.prototype);
obj.i = 0;
return obj;
}
}
Are there any plans/proposals to specify user defined callable objects?
It's possible to extend Function, but it requires to specify function code as string and prevents usage of local variables.
Eg: