ES6中函数的扩展--详细总结

一、箭头函数

let fn=(num1,num2)=>{
		return num1+num2
}

	let fn=num1=>num1+num2
简写注意事项
省略小扩号:当参数只有一个时
省略大扩号:当函数体只有一句时,
当函数体只有一句时,且是return的返回值时,return省略
返回的对象格式:参数=>({ 对象})
let arr = [0, 1, 2, 3];
var obj = arr.map(item => ({ num: item }))
console.log(obj); //[ { num: 0 }, { num: 1 }, { num: 2 }, { num: 3 } ]


使用注意点

箭头函数有几个使用注意点。

(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。

(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。

上面几点中,第一点尤其值得注意。this对象的指向是可变的,但是在箭头函数中,它是固定的。
this是静态的,this始终指向函数声明时所在作用域下的this的值(箭头函数this执行的上一层作用域)

let obj = {
            age: 18,
            say: function() {
                console.log('今年我' + this.age + '岁');
            },
            grow: function() {
               
                setInterval(function() {
                    this.age++;
                    this.say(); //this指向window
                }, 3000)
            }
        }
        obj.grow();
let obj = {
            age: 18,
            say: function() {
                console.log('今年我' + this.age + '岁');
            },
            grow: function() {
                setInterval(() => {
                    this.age++;
                    this.say();
                }, 3000)
            }
        }
        obj.grow();
let obj = {
            age: 18,
            say: function() {
                console.log('今年我' + this.age + '岁');
            },
            grow: function() {
                that = this;
                setInterval(function() {
                    that.age++;
                    that.say();
                }, 3000)
            }
        }
        obj.grow();

二、函数的不定参数

function add (...args){
	var ret  = args.reduce((a,b)=>a+b);
	alert(ret);
}
// add(1);
add(2,8,1,7,3)

三、函数的拓展实参

 var arr = ['小明', '小花', '小李', '李华'];

        function missing(a, b, c, d) {
            console.log('今天开会的有', a, b, c, d);
        }
        missing(...arr);
        //使用apply的方法
        missing.apply(null, arr)

猜你喜欢

转载自blog.csdn.net/qq_47008195/article/details/107943032