數據類型
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); // Array[3]
// [1, 2, 3]
function fn(a, b, ...args){
return args;
}
fn(1, 2, 3, 4, 5); // Array[3]
// [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 關鍵字調用就是構造函數,使用構造函數可以 實例化 一個對象
函數的返回值有兩種可能
1.顯式調用 return 返回 return 後表達式的求值
2.沒有調用 return 返回 undefined
function People(name, age) {
this.name = name;
this.age = age;
}
var people = new People('Byron', 26);
構造函數返回值
1.沒有返回值
2.簡單數據類型
3.對象類型
前兩種情況構造函數返回構造對象的實例,實例化對象正是利用的這個特性
第三種構造函數和普通函數表現一致,返回 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 和作用域
作用域可以通俗的理解
1.我是誰
2.我有哪些馬仔
其中我是誰的回答就是 this
馬仔就是我的局部變量
this 場景
普通函數
1.嚴格模式:undefined
2.非嚴格模式: 全局對象
3.Node: global
4.浏覽器: 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 返回一個新函數,函數的作用域為 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 的場景,繼承有兩個目標,子類需要得到父類的:
1.對象的屬性
2.對象的方法
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);
});
閉包
閉包由兩部分組成
1.函數
2.環境:函數創建時作用域內的局部變量
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);
以上內容是小編給大家介紹的JavaScript語言精粹經典實例(整理篇)的全部敘述,希望對大家有所幫助!