3 ms·
I'm curious as to why they have 'this.' to access class fields. JavaScript uses this because the architecture for accessing fields predates the existence of cl
by Lerc 5y ago
I'm curious as to why they have 'this.' to access class fields.
JavaScript uses this because the architecture for accessing fields predates the existence of classes (even then I feel it should be extended to allow fields be accessed without 'this.' if the field and usage exist within the same class definition.)
Surely a compiler should be smart enough to not require a 'this.' if the name is in the scope of the class and not hidden behind something like a parameter with the same name.
- eyelidlessness 5y ago> JavaScript uses this Python goes one further and requires you explicitly name your this (commonly self) as a parameter. Which is one thing I particularly like about Python, as it’s clear class instance methods are just sugar over plain functions/routines without any magic. I find the Java-style name resolution that doesn’t require qualification utterly confusing. It would be especially weird/probably a footgun in a JS-like language where functions are frequently used as values and where their names can be shadowed locally.
- zarzavat 5y agoI dislike implicit 'this' immensely. It is very common for local variables to shadow instance variables, e.g. in a constructor. Habitual use of shadowing can lead to bugs, for instance if you mistype a local variable declaration a later use of the intended name might default to the instance variable. Ruby is my favourite with @foo, it's concise but explicit. Because of this, languages with implicit this tend to have a convention such as "instance variables must start with an underscore", which is just a poor man's sigil. Here's an example: In early versions of Swift, using print("hello world") in a UI class would open a print dialog, because it dispatched the print: instance method on NSView, instead of the global print function.
- deleted 5y ago[deleted]
- ford_o 5y agoMistyped variable will lead to unused variable warning. The swift example is problem of API, not shadowing.
- zarzavat 5y agoIt is possible to attempt use a variable more than once. The Swift example was caused by shadowing. There was a global print() function and a instance print() method (taking one parameter, sender: AnyObject). If you called print() in a class not descending from NSView it printed the string in the console as expected. But if you called it in a class descending from NSView you got a print dialog as the instance method shadowed the global function. They fixed the issue long ago of course.