要想学好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。