DIV CSS 佈局教程網

JavaScript 語言精粹:核心概念與經典範例整理
編輯:關於JavaScript     

JavaScript 是前端開發中非常重要的語言。本文整理資料型別、變數、函式、物件、原型、this、繼承、閉包與柯里化等核心概念,並搭配簡潔範例,方便快速複習。

資料型別

JavaScript 可以識別多種值型別。使用 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"

變數與作用域

var 具有函式作用域,let 與 const 具有區塊作用域。只宣告不賦值時,變數預設值為 undefined。

var globalVar = 1;

function fn() {
  var fnVar = 2;

  if (fnVar > 10) {
    let blockVar = 3;
    globalVar2 = 4;
  }
}

const 宣告的是不可重新指派的變數,但物件內部屬性仍可修改。

const num = 1;
const obj = { prop: "value" };

num = 2;       // TypeError
obj.prop = "value2";
obj = [];      // TypeError

變數提升

在 JavaScript 中,可以先使用後宣告的變數而不會直接報錯,這稱為變數提升。

console.log(a); // undefined
var a = 2;

函式

函式可以透過函式宣告、函式表達式、箭頭函式等方式建立。

function fn1() {}

var fn2 = function () {};

var fn3 = (param) => {};

function fn4(...args) {
  return args;
}

function fn5(a = 2, b = 3) {
  return a + b;
}

物件與原型

物件是可變的鍵值集合。每個函式都有 prototype,每個物件也可透過 __proto__ 找到原型。

var obj = {
  prop: "value",
  fn: function () {}
};

function Person(name) {
  this.name = name;
}

Person.prototype.print = function () {
  console.log(this.name);
};

var p1 = new Person("Byron");

this 與 call、apply、bind

this 的值取決於函式呼叫方式。bind 會回傳一個綁定 this 的新函式。

function fn() {
  this.i = 0;

  setInterval(function () {
    console.log(this.i++);
  }.bind(this), 500);
}

繼承

可以透過 Object.create 建立原型鏈,模擬物件導向中的繼承。

function inherits(child, parent) {
  var prototype = Object.create(parent.prototype);
  prototype.constructor = child.prototype.constructor;
  child.prototype = prototype;
}

ES6 的 class 語法讓繼承更直覺。

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

閉包與高階函式

閉包讓函式可以記住建立時的作用域環境。

function makeCounter(init) {
  var count = init || 0;

  return function () {
    return ++count;
  };
}

var counter = makeCounter(10);

柯里化與尾遞歸

柯里化允許用部分參數產生新函式;尾遞歸則可減少部分呼叫堆疊壓力。

function isType(type) {
  return function (obj) {
    return Object.prototype.toString.call(obj) === "[object " + type + "]";
  };
}

var isNumber = isType("Number");

掌握這些核心概念後,再搭配實際專案練習,就能更穩定地理解 JavaScript 的執行邏輯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved