ES6函数参数

在一些开发语言中,都把函数作为语言的一等公民。对于编写代码来说,函数可以很容易的把类似的代码放在一起,使用的时候统一调用,下面我就简单介绍一下ES6中,对函数参数的处理和新增内容。

一、参数默认值

1、es5中处理

function foo(x,y){
    console.log(x,y)
}
foo("hello") // hello undefind
function 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 world
foo("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 undefind
function 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 5
foo({x:1}) // 1 5
foo({x:1,y:2}) // 1 2
foo() // 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") // GET
ajax("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 = 2
function foo(x,y=x){
    console.log(y)
}
foo(2) // 2
let x = 1
function foo(y=x){
    let x=2
    console.log(y)
}
foo() // 1
function foo(y=x){
    let x=2
    console.log(y)
}
foo() // Uncaught ReferenceError: x is not defined

五、函数name属性

function foo(){}
console.log(foo.name) // foo
console.log((new Function).name) // anonymous
function foo(){
    console.log(this)
}
foo.bind({name:"lilei"})() // {name:"lilei"} bind用于重指向函数this
function foo(x,y){
    console.log(this,x,y)
}
foo.bind({name:"lilei"})(1,2) // {name:"lilei"} 1 2 

console.log(foo.bind({}).name) // bound foo
console.log((function(){}).bind({}).name) // bound

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鹰3995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值