JavaScript 是弱類型語言,但並非沒有類型。它能識別以下 7 種不同的值:
可使用 typeof 判斷數據類型,它會回傳一個字串,但並非所有結果都符合預期:
typeof false // "boolean"
typeof .2 // "number"
typeof NaN // "number"
typeof '' // "string"
typeof undefined // "undefined"
typeof Symbol() // "symbol"
typeof new Date() // "object"
typeof [] // "object"
typeof alert // "function"
typeof null // "object"
typeof not_defined_var // "undefined"
在程式中,我們用變量為值命名,變量的名稱稱為 identifiers。
var:函數作用域let:塊作用域(block scope local variable)var global_var = 1;
function fn () {
var fn_var = 2;
if(fn_var > 10){
let block_var = 3;
global_var2 = 4;
}
}
只聲明不賦值,變量的預設值為 undefined。const 關鍵字可聲明不可變變量,同樣為塊作用域,但對「不可變」的理解在物件上需特別注意:
const num = 1;
const obj = { prop: 'value' };
num = 2; // Uncaught TypeError: Assignment to constant variable.
obj['prop'] = 'value2';
obj = []; // Uncaught TypeError: Assignment to constant variable.
JavaScript 中可以引用稍後才聲明的變量而不會報錯,這一概念稱為變量聲明提升(hoisting):
console.log(a); // undefined
var a = 2;
等同於:
var a;
console.log(a);
a = 2;
一個函數就是一段可被外部程式碼呼叫(或由函數本身遞迴呼叫)的子程序。
function fn(){}
var fn = function(){}
var fn = new Function(arg1, arg2, ... argN, funcBody)
var fn = (param) => {}
function foo() { return arguments; }
foo(1, 2, 3); // Arguments[3]
// { "0": 1, "1": 2, "2": 3 }
function foo(...args) { return args; }
foo(1, 2, 3); // [1, 2, 3]
function fn(a, b, ...args){ return args; }
fn(1, 2, 3, 4, 5); // [3, 4, 5]
function fn (a = 2, b = 3) { return a + b; }
fn(2, 3); // 5
fn(2); // 5
fn(); // 5
JavaScript 中的物件是可變的鍵控集合(keyed collections)。
var obj = { prop: 'value', fn: function(){} };
var date = new Date();
構造函數與普通函數並無本質區別,用 new 呼叫它就是構造函數,可用來實例化一個物件。函數返回值有兩種可能:顯式呼叫 return 時回傳表達式求值;沒有 return 時回傳 undefined。
function People(name, age) {
this.name = name;
this.age = age;
}
var people = new People('Byron', 26);
構造函數的返回值有三種情況:沒有返回值、簡單數據類型、物件類型。前兩種情況下構造函數會回傳實例本身,實例化正是利用這一特性;第三種則與普通函數一致,回傳 return 後表達式的結果。
prototype 物件屬性,其中有一個 constructor 屬性,預設指向函數本身__proto__ 屬性,指向其父類型的 prototypefunction Person(name) { this.name = name; }
Person.prototype.print = function () { console.log(this.name); };
var p1 = new Person('Byron');
var p2 = new Person('Casper');
p1.print();
p2.print();
作用域可以通俗地理解為兩個問題:「我是誰」以及「我有哪些馬仔」。其中「我是誰」對應的就是 this,而「馬仔」就是我的局部變量。
普通函數
undefinedglobal,瀏覽器為 window)構造函數:指向物件的實例
物件方法:指向物件本身
function isNumber(obj) {
return Object.prototype.toString.call(obj) === '[object Number]';
}
bind 會回傳一個新函數,其 this 指向 bind 傳入的參數:
function fn() {
this.i = 0;
setInterval(function () {
console.log(this.i++);
}.bind(this), 500)
}
fn();
箭頭函數是 ES6 的新特性,是函數表達式的簡寫,擁有詞法作用域與固定的 this 值:
function fn() {
this.i = 0;
setInterval(() => {
console.log(this.i++);
}, 500)
}
fn();
在 JavaScript 中,繼承的目標是讓子類獲得父類的屬性與方法:
function inherits(child, parent) {
var _proptotype = Object.create(parent.prototype);
_proptotype.constructor = child.prototype.constructor;
child.prototype = _proptotype;
}
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.getName = function () { return this.name; }
function English(name, age, language) {
People.call(this, name, age);
this.language = language;
}
inherits(English, People);
English.prototype.introduce = function () {
console.log('Hi, I am ' + this.getName());
console.log('I speak ' + this.language);
}
function Chinese(name, age, language) {
People.call(this, name, age);
this.language = language;
}
inherits(Chinese, People);
Chinese.prototype.introduce = function () {
console.log('你好,我是' + this.getName());
console.log('我說' + this.language);
}
var en = new English('Byron', 26, 'English');
var cn = new Chinese('色拉油', 27, '漢語');
en.introduce();
cn.introduce();
"use strict";
class People{
constructor(name, age){
this.name = name;
this.age = age;
}
getName(){
return this.name;
}
}
class English extends People{
constructor(name, age, language){
super(name, age);
this.language = language;
}
introduce(){
console.log('Hi, I am ' + this.getName());
console.log('I speak ' + this.language);
}
}
let en = new English('Byron', 26, 'English');
en.introduce();
loop: for (var i = 0; i < 10; i++) {
for (var j = 0; j < 5; j++) {
console.log(j);
if (j === 1) {
break loop;
}
}
}
console.log(i);
var x = { a:1 };
{ a:1 }
{ a:1, b:2 }
( function() {}() );
( function() {} )();
[ function() {}() ];
~ function() {}();
! function() {}();
+ function() {}();
- function() {}();
delete function() {}();
typeof function() {}();
void function() {}();
new function() {}();
new function() {};
var f = function() {}();
1, function() {}();
1 ^ function() {}();
1 > function() {}();
高階函數是把函數當作參數、或返回值為函數的函數。
[1, 2, 3, 4].forEach(function(item){ console.log(item); });
閉包由兩部分組成:函數本身,以及函數建立時作用域內的局部變量(環境)。
function makeCounter(init) {
var init = init || 0;
return function(){
return ++init;
}
}
var counter = makeCounter(10);
console.log(counter());
console.log(counter());
for (var i = 0; i < doms.length; i++) {
doms.eq(i).on('click', function (ev) {
console.log(i);
});
}
修正方式:
for (var i = 0; i < doms.length; i++) {
(function (i) {
doms.eq(i).on('click', function (ev) {
console.log(i);
});
})(i);
}
function eventBinderGenerator() {
if (window.addEventListener) {
return function (element, type, handler) {
element.addEventListener(type, hanlder, false);
}
} else {
return function (element, type, handler) {
element.attachEvent('on' + type, handler.bind(element, window.event));
}
}
}
var addEvent = eventBinderGenerator();
一種允許使用部分參數生成函數的方式:
function isType(type) {
return function(obj){
return Object.prototype.toString.call(obj) === '[object '+ type +']';
}
}
var isNumber = isType('Number');
console.log(isNumber(1));
console.log(isNumber('s'));
var isArray = isType('Array');
console.log(isArray(1));
console.log(isArray([1, 2, 3]));
function f(n) { return n * n; }
function g(n) { return n * 2; }
console.log(f(g(5)));
function pipe(f, g) {
return function () {
return f.call(null, g.apply(null, arguments));
}
}
var fn = pipe(f, g);
console.log(fn(5));
普通遞迴容易發生「棧溢出」(stack overflow)錯誤:
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
factorial(5) // 120
而尾遞迴由於只存在一個呼叫記錄,永遠不會發生「棧溢出」:
function factorial(n, total) {
if (n === 1) return total;
return factorial(n - 1, n * total);
}
factorial(5, 1) // 120
配合柯裡化減少參數:
function currying(fn, n) {
return function (m) {
return fn.call(this, m, n);
};
}
function tailFactorial(n, total) {
if (n === 1) return total;
return tailFactorial(n - 1, n * total);
}
const factorial = currying(tailFactorial, 1);
factorial(5) // 120
Function.prototype.uncurry = function () {
return this.call.bind(this);
};
把 push 通用化:
var push = Array.prototype.push.uncurry();
var arr = [];
push(arr, 1);
push(arr, 2);
push(arr, 3);
console.log(arr);