学习笔记 JavaScript ES6 函数的参数

学习内容:

  • 参数的默认值
  • 与解构赋值结合
  • length属性
  • 作用域
  • 函数的name属性

参数的默认值


function test(x, y = 'kitty') {
  console.log(x,y)
}

test('hello')
test('hello',true)
test('hello',0)

-------------
hello kitty
hello true
hello 0

细节1:函数中的参数会被默认声明

细节2:test(x, x, y),这样定义也不可以,参数名不可以重名

function test(x) {
  let x = 2 // 使用const也是一样的报错
  console.log(x)
}

test(1)

------------------------------------------------------------
错误信息:Identifier 'x' has already been declared (50:14)

细节3:默认参数的位置一定要放到最后面

// 这样是不对的
function test(x, y = 1, z) {
  console.log(x,y,z)
}

// 这样是对的
function test(x, z, y =1) {
  console.log(x,y,z)
}

与解构赋值的结合

这里之前也学习过,主要注意两边的形式要相互匹配上,否则报错的。

function test({x,y='3'}){
  console.log(x,y)
}

test({})
test({
  x:1
})

--------------
undefined '3'
1 '3'

下面的例子如果看不懂,特别是ajax参数中有一个"={}"没看懂,可以参考:

https://coding.imooc.com/learn/questiondetail/NAr19Xnwk9r6LBEz.html

ES6当中,设置函数默认值比较常用,而且大多结合着解构赋值来用

function ajax(url,{
  body = '',
  method = 'GET' 
} = {}) {

  console.log(url,method)
}

ajax('http://www.nice.com')
ajax('http://www.nice.com',{
  method : 'POST'
})

------
GET
POST

length属性

返回没有指定默认值的参数的个数

function foo(x,y,z) {
}

function foo1(x,y=1,z=2) {
}

function foo2(x=1,y=1,z=2) {
}
console.log(foo.length)
console.log(foo1.length)
console.log(foo2.length)

--------------------
3
1
0

作用域

参数被设置默认值后,就会形成一个单独的作用域

例子1:

let x = 1
function test(x, y = x) { // y = x ,这个x指向的是当前作用域里的x

  console.log(y)
}

test(2)

------
2

例子2:

let x = 1
function test(y = x) { // y = x ,这里的x未定义,则沿着作用域链上向找到x = 1

  let x = 2
  console.log(y)
}

test()

---------
1

例子3:

// let x = 1
function test(y = x) { // y = x ,这里的x未定义,则沿着作用域链上向找到x = 1

  let x = 2
  console.log(y)
}

test()

------------------------------------------
Uncaught ReferenceError: x is not defined

函数的name属性

取得函数的名字

例子1:

function test() {

}

console.log(test.name)
console.log((new Function).name)

-------------------
name
anonymous

例子2:

function test(x,y) {
  console.log(this, x, y)
}

test.bind({name : 'test'},1 ,2)()

--------------------
{name: 'test'} 1 2

例子3:

function test(x,y) {
  console.log(this, x, y)
}

console.log(test.bind().name)

--------------------
bound test

例子4:

function test(x,y) {
  console.log(this, x, y)
}

console.log((function(){}).bind({}).name)

--------------------
bound

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值