0

I am a pythonista who is learning js.

# python
class A():
    def __init__(self, a):
        self.a = a

    def main(self):
        print(self.a)

a = A(1)
b = a.main
a.main()    # 1
b()    # 1



// js
class A {
    constructor(a) {
        this.a = a;
    }
    main() {
        console.log(this.a)
    }
}

a = new A(1);
b = a.main
console.log(Object.is(b, a.main)); // true
a.main();   // 1
b(); // TypeError: Cannot read property 'a' of undefined  # why is not 1?

I know b need bind(a) like:

b = b.bind(a)

But my question is what is different between python and js? Why python can do it but js can't. I guess the reason is about underlying implementation mechanism of python and js is different, but I don't know. Thanks in advance.

Young
  • 46
  • 3
  • 2
    *"But my question is what is different between python and js?"* Because they're very different languages that do things very differently. See the answers to the linked questions for how JavaScript's `this` works. (Short version: In most cases, with a non-arrow function, it's set by how the function is *called*, not where the function is defined.) Years ago I did [a blog post](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html) on this as well (very anemic blog :-) ). – T.J. Crowder Feb 09 '20 at 13:08
  • Thanks a lot! After reading your blog post, I came to this conclusion: because object in JS has not method, the keyword "this" in function does not bind to any object defaultly...right? – Young Feb 09 '20 at 16:03
  • Basically, yes. As of ES2015, JavaScript does have methods as distinct from functions assigned to properties, but `this` is still determined by how they're called. ES2015+ also have arrow functions, which *close over* `this` rather than having their own binding for it. – T.J. Crowder Feb 09 '20 at 16:06

0 Answers0