Last active
October 2, 2015 21:30
-
-
Save DmitrySoshnikov/5e424606714b0825744e to your computer and use it in GitHub Desktop.
Python vs ECMAScript default params semantics
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
# Python | |
# | |
# Closures when they are used as default params, capture bindings | |
# from the environment one level above the class. | |
# | |
x = 1 # global env | |
def wrap(): | |
x = 2 # env of wrap | |
class A(object): | |
x = 3 # env of class | |
def foo(self, x = 4, y = lambda: x): # no env of params (!) | |
x = 5 # env of foo | |
return y() # 2, from env of wrap | |
print(A().foo()) # 2 | |
print(A.x, A().x) # 3, 3 | |
wrap() |
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
// JavaScript | |
// | |
// Closures capture bindings from the scope of parameters | |
// if such name exists in the parameters list. | |
var x = 1; // global env | |
function wrap() { | |
var x = 2; // env of wrap | |
class A { | |
// x = 3, no yet env of class in ES2015 | |
foo(x = 4, y = () => x) { // env of params | |
var x = 5; // env of foo | |
return y(); // 4, from env of params | |
} | |
} | |
console.log(new A().foo()); // 4 | |
} | |
wrap(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment