JS的组成 1) 核心(ECMAScript):描述了该语言的语法和基本对象。担当的是一个翻译的角色;是一个解释器;帮助计算机来读懂我们写的程序;实现加减乘除, 定义变量; 2) 文档对象模型(DOM):描述了处理网页内容的方法和接口。文档指的就是网页;把网页变成一个JS可以操作的对象;给了JS可以操作页面元素的能力; 3) 浏览器对象模型(BOM):描述了与浏览器进行交互的方法和接口。给了JS操作浏览器的能力;
var name = ‘Emily‘ while (true) { var name = ‘Anthony‘ console.log(name) //Anthony break } console.log(name) //Anthony
let name = ‘Emily‘ while (true) { let name = ‘Anthony‘ console.log(name) //Anthony break } console.log(name) //Emily
使用var两次输出都是"Anthony",这是因为ES5只有全局作用域和函数作用域,没有块级作用域,这带来很多不合理的场景。第一种场景就是你现在看到的内层变量覆盖外层变量。而let则实际上为JavaScript新增了块级作用域。用它所声明的变量,只在let命令所在的代码块内有效。
那么你可能就会理解下面的代码为什么用let取代var了。
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10
var a = []; for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 6
const也用来声明变量,但是声明的是常量。一旦声明,常量的值就不能改变。
const PI = Math.PI PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only
const有一个很好的应用场景,就是当我们引用第三方库的时声明的变量,用const来声明可以避免未来不小心重命名而导致出现bug:
const monent = require(‘moment‘)
function animals(...types){ console.log(types) } animals(‘cat‘, ‘dog‘, ‘fish‘) //["cat", "dog", "fish"]
在ES5和Java语言中,我们可以这样组合一个字符串:
var name = ‘Your name is ‘ + first + ‘ ‘ + last + ‘.‘; var url = ‘http://localhost:3000/api/messages/‘ + id;
在ES6中,我们可以使用新的语法$ {NAME},并把它放在反引号里
var name = `Your name is ${first} ${last}. `; var url = `http://localhost:3000/api/messages/${id}`;
ES6的多行字符串是一个非常实用的功能。在ES5和Java中,我们不得不使用以下方法来表示多行字符串:
var roadPoem = ‘Then took the other, as just as fair,nt‘ + ‘And having perhaps the better claimnt‘ + ‘Because it was grassy and wanted wear,nt‘ + ‘Though as for that the passing therent‘ + ‘Had worn them really about the same,nt‘; var fourAgreements = ‘You have the right to be you.n You can only be you when you do your best.‘;
然而在ES6中,仅仅用反引号就可以解决了:
var roadPoem = `Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same,`; var fourAgreements = `You have the right to be you. You can only be you when you do your best.`;
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
let cat = ‘ken‘ let dog = ‘lili‘ let zoo = {cat: cat, dog: dog} console.log(zoo) //Object {cat: "ken", dog: "lili"}
用ES6完全可以像下面这么写:
let cat = ‘ken‘ let dog = ‘lili‘ let zoo = {cat, dog} console.log(zoo) //Object {cat: "ken", dog: "lili"}
反过来可以这么写:
let dog = {type: ‘animal‘, many: 2} let { type, many} = dog console.log(type, many) //animal 2
这个恐怕是ES6最最常用的一个新特性了,用它来写function比原来的写法要简洁清晰很多:
function(i){ return i + 1; } //ES5 (i) => i + 1 //ES6
简直是简单的不像话对吧...
如果方程比较复杂,则需要用{}把代码包起来:
function(x, y) { x++; y--; return x + y; } (x, y) => {x++; y--; return x+y}
除了看上去更简洁以外,arrow function还有一项超级无敌的功能!
长期以来,JavaScript语言的this对象一直是一个令人头痛的问题,在对象方法中使用this,必须非常小心。例如:
class Animal { constructor(){ this.type = ‘animal‘ } says(say){ setTimeout(function(){ console.log(this.type + ‘ says ‘ + say) }, 1000) } } var animal = new Animal() animal.says(‘hi‘) //undefined says hi
通过运行以上的代码,会发现运行结果并不是我们所希望的那样,这是因为setTimeout中的this指向的是全局对象。如下:
this.type = ‘hello ‘ class Animalss{ constructor(){ this.type = ‘animal‘ } says(say){ setTimeout(function(){ console.log(this.type + ‘says ‘ + say) },1000) } } var animalss = new Animalss() animalss.says(‘hi‘)//hello says hi
所以为了让它能够正确的运行,传统的解决方法有两种:
第一种是将this传给self,再用self来指代this
says(say){ var self = this; setTimeout(function(){ console.log(self.type + ‘ says ‘ + say) }, 1000)
2.第二种方法是用bind(this),即
says(say){ setTimeout(function(){ console.log(self.type + ‘ says ‘ + say) }.bind(this), 1000)
但现在我们有了箭头函数,就不需要这么麻烦了:
class Animal { constructor(){ this.type = ‘animal‘ } says(say){ setTimeout( () => { console.log(this.type + ‘ says ‘ + say) }, 1000) } } var animal = new Animal() animal.says(‘hi‘) //animal says hi
当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。
JS本身是单线程的语言,它要实现异步都是通过回调函数来实现的。
setTimeout(function(){ console.log(‘Yay!‘); }, 1000);
在ES6中,我们可以用promise重写:
var wait1000 = new Promise(function(resolve, reject) { setTimeout(resolve, 1000); }).then(function() { console.log(‘Yay!‘); });
或者用ES6的箭头函数:
var wait1000 = new Promise((resolve, reject)=> { setTimeout(resolve, 1000); }).then(()=> { console.log(‘Yay!‘); });
到目前为止,代码的行数从三行增加到五行,并没有任何明显的好处。确实,如果我们有更多的嵌套逻辑在setTimeout()回调函数中,我们将发现更多好处:
setTimeout(function(){ console.log(‘Yay!‘); setTimeout(function(){ console.log(‘Wheeyee!‘); }, 1000) }, 1000);
在ES6中我们可以用promises重写:
var wait1000 = ()=> new Promise((resolve, reject)=> {setTimeout(resolve, 1000)}); wait1000() .then(function() { console.log(‘Yay!‘) return wait1000() }) .then(function() { console.log(‘Wheeyee!‘) });
class, extends, super这三个特性涉及了ES5中最令人头疼的的几个部分:原型、构造函数,继承...你还在为它们复杂难懂的语法而烦恼吗?你还在为指针到底指向哪里而纠结万分吗?
有了ES6我们不再烦恼!
ES6提供了更接近传统语言的写法,引入了Class(类)这个概念。新的class写法让对象原型的写法更加清晰、更像面向对象编程的语法,也更加通俗易懂。
class Animal { constructor(){ this.type = ‘animal‘ } says(say){ console.log(this.type + ‘ says ‘ + say) } } let animal = new Animal() animal.says(‘hello‘) //animal says hello class Cat extends Animal { constructor(){ super() this.type = ‘cat‘ } } let cat = new Cat() cat.says(‘hello‘) //cat says hello
上面代码首先用class定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。简单地说,constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实力对象可以共享的。
Class之间可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。上面定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。
super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
ES6的继承机制,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this。
P.S 如果你写react的话,就会发现以上三个东西在最新版React中出现得很多。创建的每个component都是一个继承React.Component
的类。详见react文档
module.exports = { port: 3000, getAccounts: function() { ... } }
在ES5中,main.js需要依赖require(‘module‘) 导入module.js:
var service = require(‘module.js‘); console.log(service.port); // 3000
但在ES6中,我们将用export and import。例如,这是我们用ES6 写的module.js文件库:
export var port = 3000; export function getAccounts(url) { ... }
如果用ES6来导入到文件main.js中,我们需用import {name} from ‘my-module‘语法,例如:
import {port, getAccounts} from ‘module‘; console.log(port); // 3000
或者我们可以在main.js中把整个模块导入, 并命名为 service:
import * as service from ‘module‘; console.log(service.port); // 3000
从我个人角度来说,我觉得ES6模块是让人困惑的。但可以肯定的事,它们使语言更加灵活了。
更多的信息和例子关于ES6模块,请看 this text。不管怎样,请写模块化的JavaScript。
具体可以看文章:前端开发者不得不知的ES6十大特性
原文:https://www.cnblogs.com/xjf125/p/10373063.html