Pages

Wednesday, 26 October 2022

Python's Bound method VS. JavaScript's unbound method

The below statement is very different between Python and JavaScript wrt binding.

obj.method

JavaScript's methods are "unbound"

class A{
    f(){
        console.log(this);
    }
}
const a1 = new A();
const a2 = new A();
console.log(a1.f === a2.f); // a1.f and a2.f are the same function, NOT bound with any object
setTimeout(a1.f, 1000); // when used a a callback, "this" is lost, not "a1" anymore.
setTimeout(a1.f.bind(a1), 1000); // to solve above problem, manually binding is needed.(Ugly code?)

Python's methods are "bound"

class A:
    def f(self):
        print(self)
a1 = A()
a2 = A()
print(a1.f == a2.f) # a1.f is a method with "a1" and "A.f" bound together automatically
print(A.f == a1.f)  # A.f is a function with no binding
import threading
threading.Timer(1, a1.f).start() # a1.f has included the object "a1".

Which one do you prefer?

I like Python's style more. How about you?

No comments:

Post a Comment