Skip to content

Instantly share code, notes, and snippets.

@Shchvova
Last active October 30, 2015 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shchvova/7784f174421839613404 to your computer and use it in GitHub Desktop.
Save Shchvova/7784f174421839613404 to your computer and use it in GitHub Desktop.
class Obj:
def __init__(self):
self.a = 1
def fn(self, b, c):
print(self.a,b,c)
a = Obj()
a.fn(2, 3) # (1,2,3)
# Function.prototype.bind()
def bind(function, obj, *args):
def boundedFunction(*args2):
finalArgs = list(args + args2)
return function(obj, *finalArgs)
return boundedFunction
f = bind(Obj.fn, a, 2)
f(3) # (1,2,3)
f(4) # (1,2,4)
f = bind(Obj.fn, a, 2, 3)
f() # (1,2,3)
f = bind(Obj.fn, a) # this is actually same as a.fn
f(2,3) # (1,2,3)
# Function.prototype.call() and Function.prototype.apply()
# Difference is onlyt that this function also perform a function call
# Also, apply takes parameters as array
def call(function, obj, *args):
return function(obj, *args)
def apply(function, obj, args): # note - no unpacking with *, apply gets parameters as array already
return function(obj, *args)
call(Obj.fn, a, 2, 3) # (1,2,3)
apply(Obj.fn, a, [2, 3]) # (1,2,3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment