首先了解什么是JavaScript
JavaScript一種動(dòng)態(tài)類型吞彤、弱類型蔬咬、基于原型的客戶端腳本語言,用來給HTML網(wǎng)頁增加動(dòng)態(tài)功能谚中。(好吧渴杆,概念什么最討厭了)
動(dòng)態(tài):
在運(yùn)行時(shí)確定數(shù)據(jù)類型。變量使用之前不需要類型聲明宪塔,通常變量的類型是被賦值的那個(gè)值的類型磁奖。
弱類:
計(jì)算時(shí)可以不同類型之間對(duì)使用者透明地隱式轉(zhuǎn)換,即使類型不正確某筐,也能通過隱式轉(zhuǎn)換來得到正確的類型比搭。
原型:
新對(duì)象繼承對(duì)象(作為模版),將自身的屬性共享給新對(duì)象南誊,模版對(duì)象稱為原型身诺。這樣新對(duì)象實(shí)例化后不但可以享有自己創(chuàng)建時(shí)和運(yùn)行時(shí)定義的屬性,而且可以享有原型對(duì)象的屬性抄囚。
PS:新對(duì)象指函數(shù)霉赡,模版對(duì)象是實(shí)例對(duì)象,實(shí)例對(duì)象是不能繼承原型的幔托,函數(shù)才可以的穴亏。
JavaScript由三部分組成:
1. ECMAScript(核心)
作為核心,它規(guī)定了語言的組成部分:語法重挑、類型嗓化、語句、關(guān)鍵字谬哀、保留字刺覆、操作符、對(duì)象
PS:*不完全兼容的實(shí)現(xiàn)
2. DOM(文檔對(duì)象模型)
DOM把整個(gè)頁面映射為一個(gè)多層節(jié)點(diǎn)結(jié)果玻粪,開發(fā)人員可借助DOM提供的API隅津,輕松地刪除诬垂、添加、替換或修改任何節(jié)點(diǎn)伦仍。
PS:DOM也有級(jí)別结窘,分為DOM1、DOM2充蓝、DOM3隧枫,拓展不少規(guī)范和新接口。
3. BOM (瀏覽器對(duì)象模型)
支持可以訪問和操作瀏覽器窗口的瀏覽器對(duì)象模型谓苟,開發(fā)人員可以控制瀏覽器顯示的頁面以外的部分官脓。
PS:BOM未形成規(guī)范
什么是ES5
作為ECMAScript第五個(gè)版本(第四版因?yàn)檫^于復(fù)雜廢棄了),瀏覽器支持情況可看第一副圖涝焙,增加特性如下卑笨。
1. strict模式
嚴(yán)格模式,限制一些用法仑撞,'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:只講有什么搏存,不講是什么瑰步。
什么是ES6
ECMAScript6在保證向下兼容的前提下,提供大量新特性璧眠,目前瀏覽器兼容情況如下:
ES6特性如下:
1.塊級(jí)作用域 關(guān)鍵字let, 常量const
2.對(duì)象字面量的屬性賦值簡寫(property value shorthand)
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">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
};</pre>
3.賦值解構(gòu)
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">let singer = { first: "Bob", last: "Dylan" };
let { first: f, last: l } = singer; // 相當(dāng)于 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</pre>
4.函數(shù)參數(shù) - 默認(rèn)值、參數(shù)打包读虏、 數(shù)組展開(Default 责静、Rest 、Spread)
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">//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</pre>
5.箭頭函數(shù) Arrow functions
(1).簡化了代碼形式盖桥,默認(rèn)return表達(dá)式結(jié)果灾螃。
(2).自動(dòng)綁定語義this,即定義函數(shù)時(shí)的this揩徊。如上面例子中腰鬼,forEach的匿名函數(shù)參數(shù)中用到的this嵌赠。
6.字符串模板 Template strings
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// return "Hello Bob, how are you today?"</pre>
7. Iterators(迭代器)+ for..of
迭代器有個(gè)next方法,調(diào)用會(huì)返回:
(1).返回迭代對(duì)象的一個(gè)元素:{ done: false, value: elem }
(2).如果已到迭代對(duì)象的末端:{ done: true, value: retVal }
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">for (var n of ['a','b','c']) {
console.log(n);
}
// 打印a熄赡、b姜挺、c</pre>
8.生成器 (Generators)
9.Class
Class,有constructor彼硫、extends炊豪、super,但本質(zhì)上是語法糖(對(duì)語言的功能并沒有影響拧篮,但是更方便程序員使用)词渤。
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">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]"</pre>
10.Modules
ES6的內(nèi)置模塊功能借鑒了CommonJS和AMD各自的優(yōu)點(diǎn):
(1).具有CommonJS的精簡語法、唯一導(dǎo)出出口(single exports)和循環(huán)依賴(cyclic dependencies)的特點(diǎn)串绩。
(2).類似AMD缺虐,支持異步加載和可配置的模塊加載。
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">// 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</pre>
11.Map + Set + WeakMap + WeakSet
四種集合類型礁凡,WeakMap志笼、WeakSet作為屬性鍵的對(duì)象如果沒有別的變量在引用它們,則會(huì)被回收釋放掉把篓。
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">// 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</pre>
12.Math + Number + String + Array + Object APIs
一些新的API
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">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) })</pre>
- Proxies
使用代理(Proxy)監(jiān)聽對(duì)象的操作纫溃,然后可以做一些相應(yīng)事情。
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">var target = {};
var handler = {
get: function (receiver, name) {
return `Hello, ${name}!`;
}
};
var p = new Proxy(target, handler);
p.world === 'Hello, world!';</pre>
可監(jiān)聽的操作: get韧掩、set紊浩、has、deleteProperty疗锐、apply坊谁、construct、getOwnPropertyDescriptor滑臊、defineProperty口芍、getPrototypeOf、setPrototypeOf雇卷、enumerate鬓椭、ownKeys、preventExtensions关划、isExtensible小染。
14.Symbols
Symbol是一種基本類型。Symbol 通過調(diào)用symbol函數(shù)產(chǎn)生贮折,它接收一個(gè)可選的名字參數(shù)裤翩,該函數(shù)返回的symbol是唯一的。
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">var key = Symbol("key");
var key2 = Symbol("key");
key == key2 //false</pre>
15.Promises
Promises是處理異步操作的對(duì)象调榄,使用了 Promise 對(duì)象之后可以用一種鏈?zhǔn)秸{(diào)用的方式來組織代碼踊赠,讓代碼更加直觀(類似jQuery的deferred 對(duì)象)呵扛。
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">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');
});</pre>
** 總結(jié)**
對(duì)于ES6,在某些方式是不是重蹈ES4的覆轍筐带,變得復(fù)雜了今穿;又或許幾年后大家的接受能力變強(qiáng)了,覺得是應(yīng)該這樣了烫堤。我覺得還是不錯(cuò)的荣赶,因?yàn)樗鼈兪窍蛳录嫒莸模词箯?fù)雜語法不會(huì)用鸽斟,也能用自己熟知的方式拔创,提供的語法糖也都挺實(shí)際。