2 ms·
So let's say I have this function: function example() { console.log(this.v); }; Which I call twice: example.apply({ v: 'One' }) example.apply({ v
by Vinnl 9y ago
So let's say I have this function:
function example() { console.log(this.v); };
Which I call twice:
example.apply({ v: 'One' })
example.apply({ v: 'Two' })
How can code analysis tell you the value of `this`?
- aljarry 9y agoIt's only working inside of EC6 classes.
- Vinnl 9y agoWell, how about this then: class ExampleClass { example() { console.log(this.v); } } Called as such: const e = new ExampleClass(); e.example.apply({ v: 'One' }); e.example.apply({ v: 'Two' });
- aljarry 9y agoI don't see how could it support properties added at runtime. I'd wager it supports only the properties defined inside of the class.
- DougBTX 9y agoWith the --noImplicitThis flag set, then the first line will fail to compile, with an error: 'this' implicitly has type 'any' because it does not have a type annotation. That error can be fixed by specifying an explicit type annotation for this: function example(this: { v: string }) { console.log(this.v); }; However, the type checking for apply is still too weak to produce any useful errors, as even with the above type annotation, this will still compile: example.apply({ b: 3 }) The type of apply is currently: Function.apply(this: Function, thisArg: any, argArray?: any): any It accepts basically any arguments. In future perhaps they will make this stricter, more discussion here: https://github.com/Microsoft/TypeScript/issues/212 https://github.com/Microsoft/TypeScript/issues/212
- jfaat 9y agoI don’t think anyone mentioned typescript, which is statically typed and therefore can provide a noImplicitThis check in its linter. AFAIK eslint doesn’t provide that option.