要想學好JavaScript除了基本的JavaScript知識點外,做爲JavaScript的第一等公民——函數,咱們要深刻的瞭解。函數的多變來源於參數的靈活多變和返回值的多變。若是參數是通常的數據類型或通常對象,這樣的函數就是普通函數;若是函數的參數是函數,這就是咱們所要知道的高級函數;若是建立的函數調用另一部分(變量和參數已經預置),這樣的函數就是偏函數。javascript
此外,還有一點就是可選參數(optional parameter)的使用。vue
有函數名,參數,返回值,同名覆蓋。示例代碼以下:java
function add(a, b) { return a + b; }
沒有函數名,能夠把函數賦值給變量和函數,或者做爲回調函數使用。很是特殊的就是當即執行函數和閉包。git
當即執行函數示例代碼以下:es6
(function(){ console.log(1) })()
閉包示例代碼以下:github
var func = (function() { var i = 1; return function() { console.log(i); } })()
高級函數就是能夠把函數做爲參數和返回值的函數。如上面的閉包。ECMAScript中也提供大量的高級函數如forEach(), every(), some(), reduce()等等。閉包
function isType(type) { return function(obj) { return toString.call(obj) === "[object " + type + "]" } } var isString = isType('String'); var isFunction = isType('Function');
相信,研究過vue.js等常見庫源碼的同窗不會陌生吧。app
箭頭函數不綁定本身的this,arguments,super。因此它不適合作方法函數,構造函數,也不適合用call,apply改變this。但它的特色就是更短,和解決匿名函數中this指向全局做用域的問題函數
window.name = 'window'; var robot = { name: 'qq', print: function() { setTimeout(function() { console.log(this.name); }, 300) } }; // 修改1,用bind修改this指向 var robot = { name: 'qq', print: function() { setTimeout(function() { console.log(this.name); }.bind(this), 300) } }; // 修改2,使用箭頭函數 var robot = { name: 'qq', print: function() { setTimeout(() => { console.log(this.name); }, 300) } };
想了解更多箭頭函數能夠看MDNthis
function add(a, b) { reutrn a + b; }
function add() { var argv = Array.prototype.slice.apply(arguments); return argv.length > 0 ? argv.reduce(function(acc, v) { return acc+=v}): ''; }
function sub(a, b) { a = a || 0; b = b || 0; return a - b; }
var option = { width: 10, height: 10 } function area(opt) { this.width = opt.width || 1; this.height = opt.height || 1; return this.width * this.height }
對象參數比較常見,常出如今jQuery插件,vue插件等中。
ES5實現可選參數,咱們須要使用arguments。使用指定範圍的可選參數咱們通常使用發對象參數,寫過jQuery等插件的應該印象深入。
在ES6中,參數默認值,省略參數操做使用比較簡便。示例代碼以下:
var area = (width=1, height=1) => width*height
在ES6中,使用可選參數。示例代碼以下:
var add = (...nums) => { var numArr = [].concat(nums) return numArr.reduce((acc, v) => acc += v) }
myFunc = function({x = 5,y = 8,z = 13} = {x:1,y:2,z:3}) { console.log(x,y,z); }; myFunc(); //1 2 3 (默認值爲對象字面量) myFunc({}); //5 8 13 (默認值爲對象自己)
function add(a, b) { return a + b }
function Robot(name) { this.name = name } Robot.prototype.init = function() { return { say: function () { console.log('My name is ' + this.name) }.bind(this), dance: function(danceName) { console.log('My dance name is ' + danceName) } }; } var robotA = new Robot('A'); robotA.init().say(); // "My name is A" var robotB = new Robot('B'); robotB.init().say(); // "My name is B"
無論是寫原生仍是jQuery插件,亦或其餘插件,這種狀況都很多見。更深刻的瞭解能夠參考jQuery源碼。
這個咱們最爲熟悉的莫過於閉包。具體可參考
老生常談之閉包
JS: How can you accept optional parameters?
Named and Optional Arguments in JavaScript
How to use optional arguments in functions (with optional callback)
後續可能還會繼續修改,也歡迎各位批評指正。有問題或者有其餘想法的能夠在個人GitHub上pr。