透过Python反补ES6

栏目: Python · 发布时间: 4年前

内容简介:原文:“你学ES6了吗?“每当被人这么问的时候,我总会感到有一种压力。事实上,我在

原文: How Python can help you learn ES6

“你学ES6了吗?“

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

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

Python与ES6的基本差异

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

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

透过 <a href='https://www.codercto.com/topics/20097.html'>Python</a> 反补ES6

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

透过Python反补ES6

函数或者...方法?

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');
  }
}
复制代码
# Python
# 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 中创建作用域?它们使用什么类型的作用域?查看下面这个表格:

透过Python反补ES6

模板字符串

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

完形填空读起来像:

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 的出现,J avaScript 也引入了设置参数默认值。

// 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了......:sweat_smile::sweat_smile::sweat_smile:


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Linked

Linked

Albert-Laszlo Barabasi / Plume / 2003-4-29 / GBP 11.24

A cocktail party. A terrorist cell. Ancient bacteria. An international conglomerate. All are networks, and all are a part of a surprising scientific revolution. Albert-L&aacuteszló Barab&a......一起来看看 《Linked》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具