本教程操作环境:windows7系统、dell g3电脑。
ecmascript是一种由ecma国际通过ecma-262标准化的脚本程序设计语言。这种语言在万维网上应用广泛,它往往被称为javascript或jscript,所以它可以理解为是javascript的一个标准,但实际上后两者是ecma-262标准的实现和扩展。
什么是es5作为ecmascript第五个版本(第四版因为过于复杂废弃了),浏览器支持情况可看第一副图,增加特性如下。
1. strict模式
严格模式,限制一些用法,'use strict';
2. array增加方法
增加了every、some 、foreach、filter 、indexof、lastindexof、isarray、map、reduce、reduceright方法 ps: 还有其他方法 function.prototype.bind、string.prototype.trim、date.now
3. object方法
object.getprototypeof
object.create
object.getownpropertynames
object.defineproperty
object.getownpropertydescriptor
object.defineproperties
object.keys
object.preventextensions / object.isextensible
object.seal / object.issealed
object.freeze / object.isfrozen
ps:只讲有什么,不讲是什么。
什么是es6ecmascript6在保证向下兼容的前提下,提供大量新特性,目前浏览器兼容情况如下: es6特性如下:
1.块级作用域关键字let,常量const
2.对象字面量的属性赋值简写(property value shorthand)
var obj = { // __proto__ __proto__: theprotoobj, // shorthand for ‘handler: handler’ handler, // method definitions tostring() { // super calls return "d " + super.tostring(); }, // computed (dynamic) property names [ 'prop_' + (() => 42)() ]: 42};
3.赋值解构
let singer = { first: "bob", last: "dylan" };let { first: f, last: l } = singer; // 相当于 f = "bob", l = "dylan"let [all, year, month, day] = /^(dddd)-(dd)-(dd)$/.exec("2015-10-25");let [x, y] = [1, 2, 3]; // x = 1, y = 2
4.函数参数 - 默认值、参数打包、 数组展开(default 、rest 、spread)
//defaultfunction findartist(name='lu', age='26') { ...}//restfunction f(x, ...y) { // y is an array return x * y.length;}f(3, "hello", true) == 6//spreadfunction f(x, y, z) { return x + y + z;}// pass each elem of array as argumentf(...[1,2,3]) == 6
5.箭头函数 arrow functions
(1).简化了代码形式,默认return表达式结果。
(2).自动绑定语义this,即定义函数时的this。如上面例子中,foreach的匿名函数参数中用到的this。
6.字符串模板 template strings
var name = "bob", time = "today";`hello ${name}, how are you ${time}?`// return "hello bob, how are you today?"
7. iterators(迭代器)+ for..of迭代器有个next方法,调用会返回:
(1).返回迭代对象的一个元素:{ done: false, value: elem }
(2).如果已到迭代对象的末端:{ done: true, value: retval }
for (var n of ['a','b','c']) { console.log(n);}// 打印a、b、c
8.生成器 (generators)
9.class
class,有constructor、extends、super,但本质上是语法糖(对语言的功能并没有影响,但是更方便程序员使用)。
class artist { constructor(name) { this.name = name; } perform() { return this.name + " performs "; }}class singer extends artist { constructor(name, song) { super.constructor(name); this.song = song; } perform() { return super.perform() + "[" + this.song + "]"; }}let james = new singer("etta james", "at last");james instanceof artist; // truejames instanceof singer; // truejames.perform(); // "etta james performs [at last]"
10.modules
es6的内置模块功能借鉴了commonjs和amd各自的优点: (1).具有commonjs的精简语法、唯一导出出口(single exports)和循环依赖(cyclic dependencies)的特点。 (2).类似amd,支持异步加载和可配置的模块加载。
// lib/math.jsexport function sum(x, y) { return x + y;}export var pi = 3.141593;// app.jsimport * as math from "lib/math";alert("2π = " + math.sum(math.pi, math.pi));// otherapp.jsimport {sum, pi} from "lib/math";alert("2π = " + sum(pi, pi));module loaders:// dynamic loading – ‘system’ is default loadersystem.import('lib/math').then(function(m) { alert("2π = " + m.sum(m.pi, m.pi));});// directly manipulate module cachesystem.get('jquery');system.set('jquery', module({$: $})); // warning: not yet finalized
11.map + set + weakmap + weakset 四种集合类型,weakmap、weakset作为属性键的对象如果没有别的变量在引用它们,则会被回收释放掉。
// setsvar s = new set();s.add("hello").add("goodbye").add("hello");s.size === 2;s.has("hello") === true;// mapsvar m = new map();m.set("hello", 42);m.set(s, 34);m.get(s) == 34;//weakmapvar wm = new weakmap();wm.set(s, { extra: 42 });wm.size === undefined// weak setsvar ws = new weakset();ws.add({ data: 42 });//because the added object has no other references, it will not be held in the set
12.math + number + string + array + object apis 一些新的api
number.epsilonnumber.isinteger(infinity) // falsenumber.isnan("nan") // falsemath.acosh(3) // 1.762747174039086math.hypot(3, 4) // 5math.imul(math.pow(2, 32) - 1, math.pow(2, 32) - 2) // 2"abcde".includes("cd") // true"abc".repeat(3) // "abcabcabc"array.from(document.queryselectorall('*')) // returns a real arrayarray.of(1, 2, 3) // similar to new array(...), but without special one-arg behavior[0, 0, 0].fill(7, 1) // [0,7,7][1, 2, 3].find(x => x == 3) // 3[1, 2, 3].findindex(x => x == 2) // 1[1, 2, 3, 4, 5].copywithin(3, 0) // [1, 2, 3, 1, 2]["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]["a", "b", "c"].keys() // iterator 0, 1, 2["a", "b", "c"].values() // iterator "a", "b", "c"object.assign(point, { origin: new point(0,0) })
13. proxies使用代理(proxy)监听对象的操作,然后可以做一些相应事情。
var target = {};var handler = { get: function (receiver, name) { return `hello, ${name}!`; }};var p = new proxy(target, handler);p.world === 'hello, world!';
可监听的操作: get、set、has、deleteproperty、apply、construct、getownpropertydescriptor、defineproperty、getprototypeof、setprototypeof、enumerate、ownkeys、preventextensions、isextensible。
14.symbols symbol是一种基本类型。symbol 通过调用symbol函数产生,它接收一个可选的名字参数,该函数返回的symbol是唯一的。
var key = symbol("key");var key2 = symbol("key");key == key2 //false
15.promises
promises是处理异步操作的对象,使用了 promise 对象之后可以用一种链式调用的方式来组织代码,让代码更加直观(类似jquery的deferred 对象)。
function fakeajax(url) { return new promise(function (resolve, reject) { // settimeouts are for effect, typically we would handle xhr if (!url) { return settimeout(reject, 1000); } return settimeout(resolve, 1000); });}// no url, promise rejectedfakeajax().then(function () { console.log('success');},function () { console.log('fail');});
总结对于es6,在某些方式是不是重蹈es4的覆辙,变得复杂了;又或许几年后大家的接受能力变强了,觉得是应该这样了。我觉得还是不错的,因为它们是向下兼容的,即使复杂语法不会用,也能用自己熟知的方式,提供的语法糖也都挺实际。 这一篇幅有些长了,就到此为止了。这一篇文章旨在讲有什么,应该是包含绝大多数内容,但没有做详细分析,部分内容来自网上资料,就不一一列出了。
推荐学习:js视频教程
以上就是es6和es5是什么的详细内容。
