lostvita / blog

60 stars 47 forks source link

透过Python反补ES6 #11

Open lostvita opened 5 years ago

lostvita commented 5 years ago

原文:How Python can help you learn ES6

“你学ES6了吗?“

每当被人这么问的时候,我总会感到有一种压力。事实上,我在Python的帮助下学习了ES6。很奇怪对吗?事实证明,这两种语言在语法上有很多是相通的,在某种程度上它们其实是大手拉小手地在发展。

在这篇文章中,你将会看到Python是怎样帮助我学习ES6的。

Python与ES6的基本差异

在我们探索JavaScriptPython之间的相似之前,我们先看一下两者之间的差异。例如,在JavaScript中,空格在编译过程不会产生影响,但在Python中却会造成报错。Python是依赖缩进去区分语句分组的。

JavaScriptPython中基本数据类型的初始值也有很大不同。查看下面表格详细了解两种语言的基本类型。你会发现除了BooleanNothing的值有一些相似之外,其他是完全不同的。 image

最后一个需要注意的是JavaScript允许类型强制。下面的代码块演示了JavaScript将数字强制转换为字符串,这在Python中是不可能的: image

函数或者...方法?

JavaScriptPython中,函数和条件语句的结构非常相似,例如:

// JS
function drSeuss(catInTheHat, thing1, thing2) {
  if (catInTheHat == true &&
    thing1 == true &&
    thing2 == true) {
    console.log('is cray');
  } else if (catInTheHat != true) {
    console.log('boring');
  } else {
    console.log('so boring');
  }
}
# PY
def dr_seuss(cat_in_the_hat, thing1, thing2):
  if cat_in_the_hat == True and
    thing2 == True and
    thing2 == True:
    print 'is cray'
  elif cat_in_the_hat != True:
    print 'boring'
  else:
    print 'so boring'

我没有过多考虑这个问题(函数还是方法),但对于JavaScript,“方法”的概念通常是构建在语言规范上的方法。Eg:Function.prototype.apply()

摘自MDN:

在很多方面函数和方法是相同的,除了下面两点关键区别:

  • 方法会隐式地传递调用它的对象(译者注:比如可以通过this访问对象)
  • 方法可以对包含在类里面的数据进行操作

因为JavaScript中不存在真正的类,下面函数和方法的例子仅用Python演示(ES6的类稍后再介绍)

# PY
def fish_and_chips():
  ingredients = ['fish', 'potatoes', 'batter']
  print 'cooking %s together' % (', '.join(ingredients))

# cooking fish, potatoes, batter

class Baking(object):
  def __init__(self, supplies):
    self.supplies = supplies

  def bakewell_tart(self):
    ingredients = ['almonds', 'raspberry', 'icing sugar']
    print self
    print 'baking %s' % (', '.join(ingredients))

# <__main__.Baking object at 0x10d6e0510>

OK,让我们看看 Python是如何促使我学习更多ES6的知识的!

块级作用域

当我第一次学习JavaScript时(在“古老的”ES5时代),我认为语言中的很多结构都创建了作用域,我还认为条件语句中的块创建了作用域,但最后发现在JavaScript中只有函数在创建作用域。

通过ES6中引入的constlet,我们拥有了块级作用域:

// JS
function simpleExample(value) {
  if (value) {
    var varValue = value;
    let letValue = value;
    console.log(varValue, letValue); // value value
  }

  // if块里面定义的varValue会提升到整个function
  console.log(varValue); // value

  // letValue不会提升到if块之外
  console.log(letValue); // Uncaught ReferenceError: letValue is not defined
}

还有什么能在JavaScriptES6Python中创建作用域?它们使用什么类型的作用域?查看下面这个表格:

模板字符串

我经常认为模板字符串是完形填空,句子中缺少单词,你可以往这些空格填入任何你想写的内容,只需要保证它符合指定的单词类型即可:名词、动词、形容词等。

完形填空读起来像:

mothers sit around burping. Last summer, my little brother fell in a/an hairdo and got poison palmtree all over his butt. My family is going to Winsconsin, and I will..

与完形填空相似,模板字符串里面允许嵌入表达式。

是的,这些在ES6发布之前就已经存在于Python中了。实际上我已经先学习了Python的字符串插值,这使得我更容易理解ES6的模板字符串。

// JS
let exclamation = 'Whoa!';
let sentence = `They are really similar to Python.`;

console.log(`Template Literals: ${exclamation} ${sentence}`);
// output: Whoa! They are really similar to Python.
# PY
print '.format(): {} {}'.format('Yup.', 'Quite!')
# output: .format(): Yup. Quite!

默认参数

是的,Python一直有这个特性。设置函数参数的默认值,这对于避免参数缺失引起报错非常有效,随着ES6的出现,JavaScript也引入了设置参数默认值。

// JS
function nom(food="ice cream") {
  console.log(`Time to eat ${food}`);
}

nom(); // Time to eat ice cream
# python
def nom(food="ice cream"):
  print 'Time to eat {}'.format(food)

nom() # Time to eat ice cream

rest参数 & *args

Rest参数语法允许我们将不确定数量的参数表示为数组。在Python里面叫做*args,也是我在ES6之前就已经学习的知识。

请查看这两种语言是如何将参数封装在一个有序包里面的:

// JS
function joke(question, ...phrases) {
  console.log(question);
  for (let i = 0; i > phrases.length; i++) {
    console.log(phrases[i]);
  }
}

let es6Joke = "Why does JS single out one parameter?"
joke(es6Joke, "Because it doesn't", 'really like', 'all the REST of them!');
// output: 
// Why does JS single out one parameter?
// Because it doesn't
// really like
// all the REST of them!
# PY
def pirate_joke(question, *args):
  print question
  for arg in args:
    print arg

python_joke = "What's a Pyrate's favorite parameter?"

pirate_joke(python_joke, "*args!", "*arrgs!", "*arrrgs!")

# What's a Pyrate's favorite parameter?
# *args!
# *arrgs!
# *arrrgs!

现在我们来看看原型继承。ES6的类实际是基于ES5的原型链实现的语法糖,因此,我们可以用ES6类做的事情与用ES5原型做的事情没有太大的不同。

Python有内置的类,允许我们可以快速而简单地进行面向对象编程。但JavaScript中的原型总令我非常困惑,不过将PythonES6的类型放在一块对比确实对我很有意义。

MDN对JavaScript的原型做了解释:

当谈到继承时,JavaScript 只有一种结构:对象。每个实例对象( object )都有一个私有属性(称之为 __proto__ )指向它的构造函数的原型对象(prototype)。该原型对象也有一个自己的原型对象( __proto__ ) ,层层向上直到一个对象的原型对象为 null。根据定义,null 没有原型,并作为这个原型链中的最后一个环节。

让我们看一下基于原型链的ES6的类:

// JS
class Mammal {
  constructor() {
    this.neocortex = true;
  }
}

class Cat extends Mammal {
  constructor(name, years) {
    super();
    this.name = name;
    this.years = years;
  }

  eat(food) {
    console.log('nom ' + food);
  }
}

let fryCat = new Cat('Fry', 7);
fryCat.eat('steak');
# PY
class Mammal(object):
  neo_cortex = True

class Cat(Mammal):
  def __init__(self, name, years):
    self.name = name
    self.years = years

  def eat(food):
    print 'nom %s' % (food)

fry_cat = Cat('Fry', 7)
fry_cat.eat('steak')

ES6的类和ES5原型链之间的一个重大区别是:使用类比使用原型链更容易实现继承。这跟python的结构非常相似,真棒!

呐!你看到了,一堆关于Python如何帮助我学习ES6的例子。通常在编程语言中,存在许多差异,但也有很多相似,正是这些相似的东西,帮助了我们更容易地学习新语言!

译者说

JavaScriptPython同为脚本语言界的翘楚,在各自的领域称霸一方。如果你同时学习了PythonJS,回过头细细对比下,你会惊奇地发现两者竟然如此高度相似,JavaScript似乎一直在向Python“看齐”。

你会发现,基础数据类型方面极相似:都有SetList对应ArrayDictionary对应Map;都有闭包和匿名函数的概念以及很多的JavaScript开源库都推崇去分号的写法...

语法层面的相似,有助于我们快速掌握ES6,将对Python的理解应用到JavaScript上,也有助于我们理解ES6的设计思想!

想到这,有一种抑制不住的兴奋,对于我们这些前端er,学习Python其实也是个优势。我们也可以像作者那这样,透过ES6,反过来辅助Python的学习。

不说那么多,我要去写python了......😅😅😅