Last active
October 30, 2015 16:16
-
-
Save Shchvova/7784f174421839613404 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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