es6(基础八) 函数的扩展

一、函数参数的默认值

    function fn(obj=xx)

    传统的默认值

{
	function fn(obj){
		var obj = obj || {};
		obj.username = '张三';
		return obj.username;
	}
	console.info(fn());//张三
}

    es6的默认值

{
	function fn(obj={"username":'张三'}){
		return obj;
	}
	//等价于
	function fn(obj={}){
		obj["username"] = "张三";
		return obj;
	}
	console.info(fn());//{username: "张三"}
}
{
	let fn = function(obj){
		var obj = obj || {};
		obj.username = "张三";
		return obj.username;
	}
	console.info(fn());//张三
	let fnEs6 = (obj={})=>{
		obj.username = '张三';
		return obj.username;
	}
	console.info(fnEs6());//张三
}

二、函数作用域

{
	let x = '你好';
	function fn(x,y=x){
		console.info(x,y);//undefined  undefined
	}
	fn();
}

三、rest (...)

{
	function fn(a,b,...c){
		console.info(a,b,c,c.length);//1 2 (7) [3, 4, 6, 7, 8, 9, 10] 7
	}
	fn(1,2,3,4,6,7,8,9,10)
}

四、箭头函数

{
	let fn = function(v){
		return v;
	}
	console.info(fn())//undefined
	//只有一个参数跟函数体只有一条return语句,可以写成如下
	let fnEs6 = v=>v
	console.info(fnEs6(5));//5
}
{
	let fn = function(){
		return 123;
	}
	console.info(fn());//123
	let fnEs6 = ()=>123;//没有参数
	console.info(fnEs6());//123
}

箭头函数没有arguments

{
	let fn = function(){
		console.log(arguments);
	}
	fn(1,2,4)
	let fn1 = ()=>{
		console.info(arguments);//arguments is not defined
	}
	fn1(12,3,4)
}
替代方法为
var fn = (...arg) => {
        console.log(arg);
    }
    fn(2) // [2]

也不能用new方式,,否则会抛出一个错误

五、箭头函数的this

{
	let obj = {
		username:'张三',
		run:function(){
			setTimeout(function(){
				console.log(this);
				//Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}
				return this.username;
			},1000)
		}
	}
	console.info(obj.run());//undefined
	let objEs6 = {
		username:'张三',
		run:function(){
			setTimeout(()=>{
				console.log(this);//{username: "张三", run: ƒ}
				return this.username;
			},1000)
		}
	}
	console.info(objEs6.run());//undefined
}




猜你喜欢

转载自blog.csdn.net/u011705725/article/details/80750771