函数拓展
- 使用默认参数技术,初始化参数的时候,会形成一个作用域
let a = 1;
function demo(a,b=a){
console.log(a,b)
}
demo()// undefined
demo(2)// 2 2
let a = 1;
function demo(a,b=function(){a =10}()){
console.log(a,b)
}
demo();// 10 undefined
demo(2)// 10 undefined
let a = 1;
function demo(a,b=function(){a =10}()){
var a = 20;
console.log(a,b)
}
demo();// 20 undefined
demo(2)// 20 undefined
let a = 1;
function demo(a,b=function(){a =10}()){
console.log(a,b)
var a = 20;
}
demo();// 10 undefined
demo(2)// 10 undefined
- 参数默认值与解构语法,均不支持局部严格模式
// 参数默认值局部严格模式
function demo(a=1){
"use strict"
console.log(this)
}
demo()// 会报错
// 参数解构 也不能使用局部严格模式
function demo(...args){
"use strict"
console.log(args)
}
demo()
// 可以使用全局的严格模式
"use strict"
function demo(...args){
// "use strict"
console.log(args)
}
demo()
函数绑定
ES7提供了双冒号(::)来实现函数作用域的绑定(替代bind方法)。
语法:context::fn
等价于 fn.bind(context)
注意:
1、如果使用双冒号左边为空,右边是对象的方法,则等于将该方法绑定在该对象上::o
2、由于双冒号运算符返回的还是原对象,因此可以使用链接调用
let divs = document.getElementsByTagName("div");
// 解构 forEach
let {forEach} = Array.prototype;
// forEach.call(divs,function(...args){
// console.log(args,121)
// })
// // :: 绑定作用域
divs::forEach(function(...args) {
console.log(args)
})// 会进行报错
箭头函数
箭头函数数式ES6 新增的一种函数,只能通过函数表达式的形式定义。
语法:()=>{} , 由三部分组成:参数集合,箭头,函数体
四个特点: 1、箭头函数无法使用arguments,可以使用获取剩余剩余参数语法替代.
// 箭头函数
// let demo = (...args) => {
// // 不能使用arguments
// // console.log(arguments)
// console.log(args)
// };
// demo(1, 2, 3)
2、箭头函数不能作为构造函数。
// 不能作为构造函数的
// let Player = function(name) {
// this.name = name;
// }
// let Player = (name) => {
// this.name = name;
// }
// new Player('ickt')
3、箭头函数的作用域永远是定义时的作用域。
let obj ={
fn1(){
console.log(this)
},
fn2:()=>{
console.log(this)
}
}
obj.fn1();// obj
obj.fn2()//window
4、箭头函数不能作为generator函数,内部不能使用yeild关键字。
// 不能作为generator函数
// let demo = *() => {
// yield 1;
// }
两点省略: 1、如果参数集合中,只有一个参数,可以省略参数集合体(),如果使用解构语法、三点语法、默认参数不能省略。
// 两点省略
// let demo = msg => {
// console.log(msg)
// }
// 三个点语法不能省略参数集合
// let demo = (...args) => {
// console.log(args)
// }
// demo('hello')
// 解构语法不能省略
// let demo = ({ color }) => {
// console.log(color)
// }
// demo({ color: 'red' })
// 默认参数语法不能省略
// let demo = (msg = 'ickt') => {
// console.log(msg)
// }
// demo()
2、如果函数体中,只有一句话或者返回值,可以省略函数体{}以及return关键字。 注意:返回的如果是对象,外部要加().
// 省略函数体
// let add = (a, b) => {
// return a + b;
// }
// let add = (a, b) => a + b;
// 返回是对象要加上()
// let add = (a, b) => ({ a, b })
// console.log(add(1, 2))
箭头函数的作用域永远是定义时的作用域,因此不受严格模式,call,bind,apply方法的影响。 想改变箭头函数作用域:将箭头函数定义在一个普通函数中。想改变这个普通函数作用域,我们可以改变箭头函数的作用域。
来源:oschina
链接:https://my.oschina.net/u/4162046/blog/3212280