在一些开发语言中,都把函数作为语言的一等公民。对于编写代码来说,函数能够很容易的把相似的代码放在一起,应用的时候对立调用,上面我就简略介绍一下ES6中,对函数参数的解决和新增内容。
一、参数默认值
1、es5中解决
function foo(x,y){ console.log(x,y)}foo("hello") // hello undefindfunction foo(x,y){ y = y || "world" // 能够在es5中实现默认参数性能,然而对于空字符串或者0等,在js判断中判断为false的时候,还需独自判断 console.log(x,y) // hello world}foo("hello")
2、es6中解决:同样恪守惰性赋值准则
function foo(x,y="world"){ console.log(x,y)}foo("hello") // hello worldfoo("hello",0) // hello 0
3、默认值要放在参数最初
function foo(x,y=5,z){ console.log(x,y,z)}foo(1,2,3) // 1 2 3 foo(1,2) // 1,2 undefindfunction foo(x,y,z=5){ console.log(x,y,z)}foo(1,2,3) // 1 2 3 foo(1,2) // 1 2 5
二、与解构赋值联合(模式要齐全一样)
function foo({x,y=5}){ console.log(x,y)}foo({}) // undefind 5foo({x:1}) // 1 5foo({x:1,y:2}) // 1 2foo() // Uncaught TypeError: Cannot destructure property 'x' of 'undefined' as it is undefined.
实例:封装ajax
function ajax(url,{ body="", method="GET", headers={}}={}){ console.log(method)}ajax("https://www.baidu.com") // GETajax("https://www.baidu.com",{ method:"POST"}) // POST
三、length属性
function foo(x,y,z,v=5){ console.log(x,y)}console.log(foo.length) // 3 返回没有指定默认值参数个数
四、作用域:造成参数的固定作用域,如果定义域内没有,会沿着作用域链向上找
let x = 2function foo(x,y=x){ console.log(y)}foo(2) // 2let x = 1function foo(y=x){ let x=2 console.log(y)}foo() // 1function foo(y=x){ let x=2 console.log(y)}foo() // Uncaught ReferenceError: x is not defined
五、函数name属性
function foo(){}console.log(foo.name) // fooconsole.log((new Function).name) // anonymousfunction foo(){ console.log(this)}foo.bind({name:"lilei"})() // {name:"lilei"} bind用于重指向函数thisfunction foo(x,y){ console.log(this,x,y)}foo.bind({name:"lilei"})(1,2) // {name:"lilei"} 1 2 console.log(foo.bind({}).name) // bound fooconsole.log((function(){}).bind({}).name) // bound