一、javascript 由三部分組成#
1.ECMAScript(核心)#
它規定了語言的組成部分:法語,類型,語句,關鍵字,操作符等等。
2.DOM(文檔對象模型)#
DOM 把整個頁面映射為一個多層節點結果,開發人員可借助 DOM 提供的 API,輕鬆地刪除、添加、替換或修改任何節點。
3.BOM(瀏覽器對象模型)#
支持可以訪問和操作瀏覽器窗口的瀏覽器對象模型,開發人員可以控制瀏覽器顯示的頁面以外的部分。
二、什麼是 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:只講有什麼,不講是什麼。
2. 什麼是 ES6?#
ECMAScript6 在保證向下兼容的前提下,提供大量新特性,目前瀏覽器兼容情況如下:
ES6 特性如下:
-
塊級作用域 關鍵字 let, 常量 const
-
對象字面量的屬性賦值簡寫(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
};
- 賦值解構
let singer = { first: "Bob", last: "Dylan" };
let { first: f, last: l } = singer; // 相當於 f = "Bob", l = "Dylan"
let [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec("2015-10-25");
let [x, y] = [1, 2, 3]; // x = 1, y = 2
- 函數參數 - 默認值、參數打包、 數組展開(Default 、Rest 、Spread)
//Default
function findArtist(name='lu', age='26') {
...
}
//Rest
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
//Spread
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
- 箭頭函數 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?"
- 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
-
生成器 (Generators)
-
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; // true
james instanceof Singer; // true
james.perform(); // "Etta James performs [At last]"
- Modules
ES6 的內置模塊功能借鑒了 CommonJS 和 AMD 各自的優點:
(1) 具有 CommonJS 的精簡語法、唯一導出出口 (single exports) 和循環依賴 (cyclic dependencies) 的特點。
(2) 類似 AMD,支持異步加載和可配置的模塊加載。
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));
Module Loaders:
// Dynamic loading – ‘System’ is default loader
System.import('lib/math').then(function(m) {
alert("2π = " + m.sum(m.pi, m.pi));
});
// Directly manipulate module cache
System.get('jquery');
System.set('jquery', Module({$: $})); // WARNING: not yet finalized
- Map + Set + WeakMap + WeakSet
四種集合類型,WeakMap、WeakSet 作為屬性鍵的對象如果沒有別的變量在引用它們,則會被回收釋放掉。
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;
// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;
//WeakMap
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined
// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });//Because the added object has no other references, it will not be held in the set
- Math + Number + String + Array + Object APIs
一些新的 API
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.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 Array
Array.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) })
- 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。
- Symbols
Symbol 是一種基本類型。Symbol 透過調用 symbol 函數產生,它接收一個可選的名字參數,該函數返回的 symbol 是唯一的。
var key = Symbol("key");
var key2 = Symbol("key");
key == key2 //false
- 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 rejected
fakeAjax().then(function () {
console.log('success');
},function () {
console.log('fail');
});