[译文]透过Python反补ES6

原文:How Python can help you learn ES6javascript

“你学ES6了吗?“前端

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

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

Python与ES6的基本差别

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

JavaScriptPython中基本数据类型的初始值也有很大不一样。查看下面表格详细了解两种语言的基本类型。你会发现除了BooleanNothing的值有一些类似以外,其余是彻底不一样的。 编程

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

函数或者...方法?

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()app

摘自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了......😅😅😅

相关文章
相关标签/搜索