How to avoid hard coded this? in Decorators - javascript

I have read "How to implement a typescript decorator?" and multiple sources but there is something that i have nor been able to do with decorators.
class FooBar {
public foo(arg): void {
console.log(this);
this.bar(arg);
}
private bar(arg) : void {
console.log(this, "bar", arg);
}
}
If we invoke the function foo:
var foobar = new FooBar();
foobar.foo("test");
The object FooBar is logged in the console by console.log(this); in foo
The string "FooBar {foo: function, bar: function} bar test" is logged in the console by console.log(this, "bar", arg); in bar.
Now let's use a decorator:
function log(target: Function, key: string, value: any) {
return {
value: (...args: any[]) => {
var a = args.map(a => JSON.stringify(a)).join();
var result = value.value.apply(this, args); // How to avoid hard coded this?
var r = JSON.stringify(result);
console.log(`Call: ${key}(${a}) => ${r}`);
return result;
}
};
}
We use the same function but decorated:
class FooBar {
#log
public foo(arg): void {
console.log(this);
this.bar(arg);
}
#log
private bar(arg) : void {
console.log(this, "bar", arg);
}
}
And we invoke foo as we did before:
var foobarFoo = new FooBar();
foobarFooBar.foo("test");
The objectWindow is logged in the console by console.log(this); in foo
And bar is never invoked by foo because this.bar(arg); causes Uncaught TypeError: this.bar is not a function.
The problem is the hardcoded this inside the log decorator:
value.value.apply(this, args);
How can I conserve the original this value?

Don't use an arrow function. Use a function expression:
function log(target: Object, key: string, value: any) {
return {
value: function(...args: any[]) {
var a = args.map(a => JSON.stringify(a)).join();
var result = value.value.apply(this, args);
var r = JSON.stringify(result);
console.log(`Call: ${key}(${a}) => ${r}`);
return result;
}
};
}
That way it will use the function's this context instead of the value of this when log is called.
By the way, I would recommend editing the descriptor/value parameter and return that instead of overwriting it by returning a new descriptor. That way you keep the properties currently in the descriptor and won't overwrite what another decorator might have done to the descriptor:
function log(target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) {
var originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
var a = args.map(a => JSON.stringify(a)).join();
var result = originalMethod.apply(this, args);
var r = JSON.stringify(result);
console.log(`Call: ${key}(${a}) => ${r}`);
return result;
};
return descriptor;
}
More details in this answer - See the "Bad vs Good" example under "Example - Without Arguments > Notes"

I believe you can use
var self = this;
in order to preserve the 'this' at that specific point. Then, just use self at the later point where you would have wanted that particular this

Related

Unable to access private members when redefining method of class

When defining a private member using #, and then re-defining some member that uses this private member, you will find that you cannot use it anymore:
class Foo {
#secret = "Keyboard Cat";
method() {
console.log(this.#secret);
}
}
const target = Foo.prototype;
const key = "method";
const desc = Object.getOwnPropertyDescriptor(target, key);
const og = desc.value;
desc.value = function (...args) {
return og.apply(target, args);
};
Object.defineProperty(target, key, desc);
new Foo().method();
Uncaught TypeError: Cannot read private member #secret from an object whose class did not declare it
Why? All I have done is wrap around the original method in this case. Note that this example is a dramatic simplification of using decorators with TypeScript. How could I get around this while still being able to redefine and "change" the method?
Here's the same thing, but with a TypeScript decorator:
const Curse: MethodDecorator = (target, _, desc) => {
const og = desc.value as Function;
desc.value = function (...args: any[]) {
return og.apply(target, args);
} as any;
return desc;
};
class Foo {
#secret = "Keyboard Cat";
#Curse
method() {
console.log(this.#secret);
}
}
new Foo().method();
Playground
The mistake you made is to apply the method to the target, which is Foo.prototype, not to the new Foo instance via the this keyword:
class Foo {
#secret = "Keyboard Cat";
method() {
console.log(this.#secret);
}
}
const target = Foo.prototype;
const key = "method";
const desc = Object.getOwnPropertyDescriptor(target, key);
const orig = desc.value;
desc.value = function (...args) {
return orig.apply(this, args);
// ^^^^
};
Object.defineProperty(target, key, desc);
new Foo().method();
Foo.prototype does not have the #secret private field. You'll get the same error with
class Foo {
#secret = "Keyboard Cat";
method() {
console.log(this.#secret);
}
}
Foo.prototype.method();

Javascript object initialized with several functions: what syntax is it?

I am reviewing some Javascript code and stumbled upon a syntax that I didn't knew. The application is a React and Redux one, though I think this is plain Javascript.
The syntax I'm concerned with is the { f1(), f2(), ... } argument of combineReducers().
This is the syntax:
combineReducers({
Reducer1,
Reducer2,
...
});
ReducerN is a function, i.e.:
const Reducer1 = (state = INITIAL_STATE, action) => {
// ...
};
I get { f1(), ... } creates an object where the function name is the key and the function itself is the value, so in a browser console I tried the following:
a = () => { console.log(1) }
b = () => { console.log(2) }
o = {a, b}
and if I print o:
{a: ƒ, b: ƒ}
a: () => { console.log(1) }
b: () => { console.log(2) }
__proto__: Object
But if I try to initialize o in a single operation:
o = { () => return 1 }
or
o = { function y() { return 1 }}
they both give a syntax error.
It's the first time I see an object created with that syntax: What kind is that? Where can I find its reference?
As said previously,
combineReducers({
Reducer1,
Reducer2,
...
});
is equivalent to this in plain ES5:
combineReducers({
Reducer1: Reducer1,
Reducer2: Reducer2,
...
});
and combineReducers is concerned only with the values of the object passed in. The first form is just a shorthand for defining properties with the same name as the value. This is the reason you cannot use anonymous functions in this form. To define function members on classes and objects, you can use the following form:
class Foo {
foo() { console.log('foo'); }
bar = () => console.log('bar')
}
const a = new Foo();
a.foo();
a.bar();
const b = {
foo() { console.log('foo'); }
bar: () => console.log('bar')
};
b.foo();
b.bar();
When transpiling to plain ES5, this will generate the following:
"use strict";
var Foo = /** #class */ (function () {
function Foo() {
this.bar = function () { return console.log('bar'); };
}
Foo.prototype.foo = function () { console.log('foo'); };
return Foo;
}());
var a = new Foo();
a.foo();
a.bar();
var b = {
foo: function () { console.log('foo'); },
bar: function () { return console.log('bar'); }
};
b.foo();
b.bar();
{ f1() } is very different than { f1 }.
The latter is a shorthand of { f1: f1 } which is an object having the key 'f1' (a string) associated to the value f1 (a function). The function is not executed.
In the first example f1() is a function call. The function f1 is executed and the value it returns is used instead. But because you didn't provide a key to associate the value with and because f1() is a value that does not have a name (it is an expression that needs to be evaluated in order to get its value), JS cannot produce an object out of it.
{ f1 } can be evaluated at the compile time and turned into { f1: f1 }.
{ f1() } cannot be evaluated at the compile time. The value of f1() is available only at the run time.
This is why { f1() } is invalid code.
If you need to call f1 and use the value it returns to create an object you can do it this way:
const x = { f1: f1() }
This is the same thing as:
const v = f1();
const x = { f1: v }

How to get getter/setter name in JavaScript/TypeScript?

Getting a function name is pretty straightforward:
const func1 = function() {}
const object = {
func2: function() {}
}
console.log(func1.name);
// expected output: "func1"
console.log(object.func2.name);
// expected output: "func2"
How can I get the string name of a getter/setter, though?
class Example {
get hello() {
return 'world';
}
}
const obj = new Example();
Important note:
I don't want to use a hard-coded string:
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), 'hello')
But get the name, e.g.:
console.log(getGetterName(obj.hello))
// expected output: "hello"
That syntax sets the get function of the hello property descriptor so the name of the function will always be get you can check if the hello property has a get function on it's property descriptor with Object.getOwnPropertyDescriptor().
class Example {
get hello() {
return 'world';
}
}
/*
compiles to / runs as
var Example = (function () {
function Example() {
}
Object.defineProperty(Example.prototype, "hello", {
get: function () {
return 'world';
},
enumerable: true,
configurable: true
});
return Example;
}());
*/
const des = Object.getOwnPropertyDescriptor(Example.prototype, 'hello');
console.log(des.get.name); // get (will always be 'get')
// to check if 'hello' is a getter
function isGetter(name) {
const des = Object.getOwnPropertyDescriptor(Example.prototype, name);
return !!des && !!des.get && typeof des.get === 'function';
}
console.log(isGetter('hello')); // true
Sounds like this won't solve your ultimate issue but:
Object.getOwnPropertyDescriptor(Example.prototype, 'hello').get.name
100% answers the question "How to get getter/setter name in JavaScript/TypeScript?" and it will always be "get"
Edit:
Once you call obj.hello the getter is already called an all you have is the primitive result, but you may be able to use metadata on the property value its self.
function stringPropertyName() {
let _internal;
return (target, key) => {
Object.defineProperty(target, key, {
get: () => {
const newString = new String(_internal);
Reflect.defineMetadata('name', key, newString);
return newString;
},
set: value => {
_internal = value;
}
});
};
}
class Example1 {
#stringPropertyName()
hello = 'world';
}
const obj1 = new Example1();
console.log(Reflect.getMetadata('name', obj1.hello)); // hello
class Example2 {
_hello = 'world';
get hello() {
const newString = new String(this._hello);
Reflect.defineMetadata('name', 'hello', newString);
return newString;
}
set hello(value) {
this._hello = value;
}
}
const obj2 = new Example2();
console.log(Reflect.getMetadata('name', obj2.hello)); // hello
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.6.11/core.min.js"></script>

Class Decorator in Typescript

I'm trying to understand how class decorators work in Typescript when we wish to replace the constructor. I've seen this demo:
const log = <T>(originalConstructor: new(...args: any[]) => T) => {
function newConstructor(... args) {
console.log("Arguments: ", args.join(", "));
new originalConstructor(args);
}
newConstructor.prototype = originalConstructor.prototype;
return newConstructor;
}
#log
class Pet {
constructor(name: string, age: number) {}
}
new Pet("Azor", 12);
//Arguments: Azor, 12
Everything is understood but this line:
newConstructor.prototype = originalConstructor.prototype;
Why do we do that?
The classes like:
class Pet {
constructor(name: string, age: number) {}
dosomething() {
console.log("Something...");
}
}
Are compiled into functions when targeting ES5:
var Pet = (function () {
function Pet(name, age) {
}
Pet.prototype.dosomething = function () {
console.log("Something...");
};
return Pet;
}());
As you can seem when we use functions to define classes. The methods are added to the function's prototype.
This means that if you are going to create a new constructor (new function) you need to copy all the methods (the prototype) from the old object:
function logClass(target: any) {
// save a reference to the original constructor
const original = target;
// a utility function to generate instances of a class
function construct(constructor: any, args: any[]) {
const c: any = function () {
return constructor.apply(this, args);
};
c.prototype = constructor.prototype;
return new c();
}
// the new constructor behaviour
const newConstructor: any = function (...args: any[]) {
console.log("New: " + original.name);
return construct(original, args);
};
// copy prototype so intanceof operator still works
newConstructor.prototype = original.prototype;
// return new constructor (will override original)
return newConstructor;
}
You can learn more at "Decorators & metadata reflection in TypeScript: From Novice to Expert (Part I)"
Update
Please refer to https://github.com/remojansen/LearningTypeScript/tree/master/chapters/chapter_08 for a more recent version.

typescript: context preservation. Is it a good idea to do it such way?

I want to keep this in class methods.
I can use arrow functions, but I want to override some methods in extended class.
Now I have this solution and it works:
class Foo {
bar = "Context preserved.";
constructor() {
this.foo = this.foo.bind(this);
}
foo() {
alert(this.bar);
}
}
class Foo2 extends Foo {
foo() {
alert(this.bar + " Class extended");
}
}
class Bar {
bar = "Context lost.";
}
let foo = new Foo2();
let bar = new Bar();
foo.foo.apply(bar); // Context preserved. Class extended
Is it a good practice to do it such way? If it is, is there some keyword in typescript to do it automatically?
like
class Foo() {
public conserved foo() { }
}
which generates:
var Foo = (function () {
function Foo() {
this.foo = this.foo.bind(this);
}
Foo.prototype.foo = function () { };
return Foo;
}());
It's a valid practice and it's being used.
I'm unaware of a way to tell typescript to do this automatically, but you can search the issues for something like it.
You can have a decorator that does that for you, for example:
function construct(constructor: Function, methods: string[], args: any[]) {
var c: any = function () {
return constructor.apply(this, args);
}
c.prototype = constructor.prototype;
let instance = new c();
methods.forEach(name => {
instance[name] = instance[name].bind(instance);
});
return instance;
}
function BindMethods(constructor: Function) {
const methods = [] as string[];
Object.keys(constructor.prototype).forEach(name => {
if (typeof constructor.prototype[name] === "function") {
methods.push(name);
}
});
return (...args: any[]) => {
return construct(constructor, methods, args);
};
}
#BindMethods
class Foo {
bar = "Context preserved.";
foo() {
console.log(this.bar);
}
}
let foo = new Foo();
setTimeout(foo.foo, 10);
(code in playground)
I tested it with this simple use case and it worked just fine.

Categories

Resources