|
|
|
|
|
by spankalee
4389 days ago
|
|
No, JavaScript does not have Python's __getattr__, and obj[name] is not a substitute for it. obj[name] works if you have already either assigned a value for that name, it exists in the prototype chain, or you have defined a getter via Object.defineProperty(). It's truly no different than obj.name[1] - `name` has to already exist in some form. Python's __getattr__ [2] takes the attribute name as an argument, so it can be used to implement property access for any name, even those not known ahead of time. Ruby has something similar with method_missing, and even more with define_method and instance_eval. Dart has noSuchMethod. These are possible to implement in compile-to-JS language, but tricky to make fast. Dart's static analysis looks for all names that could be called on objects with a noSuchMethod, tries to figure out the most specific class it can add them to, then adds stubs to the JS prototypes to redirect to noSuchMethod(). A compile-to-JS Ruby could implement define_method easily enough, but method_missing is would be impossible to do the way Dart does it due to the open classes: you could dynamically add method_missing and not have the stubs available. If you want full Ruby semantics you have to abstract away method calls, which will be slow. I'm guessing the same problem exists for Python, so I wonder the same thing as the grandparent post: did they implement __getattr__ fully? [1] With the small difference in the names that are allowed.
[2] https://docs.python.org/3/reference/datamodel.html#object.__... |
|
https://github.com/PythonJS/PythonJS/blob/master/regtests/cl...
__getattr__ and __getattribute__ are implemented in the special __get__ function defined in: https://github.com/PythonJS/PythonJS/blob/master/pythonjs/ru...