DIV CSS 佈局教程網

JavaScript 核心知識點精粹總結
編輯:JavaScript基礎知識     

數據類型

JavaScript 是弱類型語言,但並非沒有類型。它能識別以下 7 種不同的值:

基本數據類型

  1. Boolean
  2. Number
  3. String
  4. null
  5. undefined
  6. Symbol

物件類型 Object

  1. Array
  2. RegExp
  3. Date
  4. Math
  5. ...

可使用 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。

聲明方式

  1. 使用 var:函數作用域
  2. 使用 let:塊作用域(block scope local variable)
  3. 直接使用:全局作用域
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;

函數

一個函數就是一段可被外部程式碼呼叫(或由函數本身遞迴呼叫)的子程序。

定義函數的四種方式

  1. 函數聲明
  2. 函數表達式
  3. Function 構造函數
  4. 箭頭函數
function fn(){}
var fn = function(){}
var fn = new Function(arg1, arg2, ... argN, funcBody)
var fn = (param) => {}

arguments

  1. arguments:一個包含傳遞給當前函數參數的、類似數組的物件
  2. arguments.length:傳給函數的參數數目
  3. arguments.caller:呼叫當前函數的函數
  4. arguments.callee:當前正在執行的函數
function foo() { return arguments; }
foo(1, 2, 3); // Arguments[3]
// { "0": 1, "1": 2, "2": 3 }

rest 參數

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]

預設參數 default

function fn (a = 2, b = 3) { return a + b; }
fn(2, 3); // 5
fn(2); // 5
fn(); // 5

物件

JavaScript 中的物件是可變的鍵控集合(keyed collections)。

定義物件

  1. 字面量
  2. 構造函數
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

  1. 每個函數都有一個 prototype 物件屬性,其中有一個 constructor 屬性,預設指向函數本身
  2. 每個物件都有一個 __proto__ 屬性,指向其父類型的 prototype
function 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 與作用域

作用域可以通俗地理解為兩個問題:「我是誰」以及「我有哪些馬仔」。其中「我是誰」對應的就是 this,而「馬仔」就是我的局部變量。

this 的場景

普通函數

  1. 嚴格模式:undefined
  2. 非嚴格模式:全局物件(Node 為 global,瀏覽器為 window)

構造函數:指向物件的實例
物件方法:指向物件本身

call & apply

  1. fn.call(context, arg1, arg2, …, argn)
  2. fn.apply(context, args)
function isNumber(obj) {
    return Object.prototype.toString.call(obj) === '[object Number]';
}

Function.prototype.bind

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();

ES6 class 與繼承

"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();

語法

label statement 標籤語句

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));

尾遞迴

  1. 尾呼叫指某函數的最後一步是呼叫另一個函數
  2. 函數呼叫自身稱為遞迴
  3. 若尾呼叫自身,就稱為尾遞迴

普通遞迴容易發生「棧溢出」(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);
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved