ES6 箭头函数

箭头函数:语义化函数
基础语法;
//传统的函数

function fun(a,b){
console.log(a*b);//6
}
fun(2,3)

//箭头函数

var  fun1 = (a,b) =>{
console.log(a*b);//6
}
fun1(2,3);

参数的传递:
1.若参数只有一个,小括号可以省略。若参数有0个或者两个以上必须要有()

var fun = a =>console.log(a);
fun(3);
//当我们语句中有return时必须加上{}

将普通函数简化为箭头函数:

```javascript
let arr[1,2,3];
console.log(arr.foo(function(x){
return x*x;
}));

//简化为箭头函数

let arr=[1,2,3];
console.log(arr.foo(x => x*x));
2如果返回值是一个对象的时候,就会认为成函数体,把返回值变成表达式的形式

```javascript
const obj = (a,b) => 
			({
				a : a,
				b : b
			})
		
		console.log( obj(1,2) )//object

this指向问题:
点击页面,使控制台输出click

var obj = {
            init: function() {
                // console.log(this);
                // this指向obj
                var that = this;
                document.addEventListener('click', function(event) {
                // console.log(this); 原this指向document,先在that指向了obj
                    that.output(event.type);
                })
            },
            output: function(value) {
                console.log(value);
            }
        }
        obj.init();

箭头函数可以理解为没有this指向;其this指向是借用父级this;其this指向是不可更改的

var obj = {
            init: function() {
                document.addEventListener('click', (event) => {
                    this.output(event.type);
                })
            },
            output: function(value) {
                console.log(value);
            }
        }
        obj.init();
var obj = {
            init: function() {
                console.log(this);
                // this指向obj
            }
        }
        obj.init();

在这里插入图片描述
现在我们使用箭头函数;(找父级作用域的this,且this指向不更改)

var obj = {
            init: () => {
                console.log(this);
                // this指向window
            }
        }
        obj.init();//this指向是不可更改的

注意:
.1.箭头函数中没有this,argument,new.target,如果要强行使用,则指向函数外层对 应的this,argument,new.target

const func = () => {
			console.log(this)
		}
		// func()   //window

		const obj = {
			fun : func,
			method : function(){
				const func = () => {
					console.log(this);
					console.log(arguments)   
				}
				func(4,5,6)
			}		
		}
		// obj.fun()  // window
		obj.method(1,2,3)   //obj

2.箭头函数没有原型,所有说占用空间非常小,不能当成构造函数来使用

console.log(func,func.prototype)   
		console.dir(func)

在这里插入图片描述
所以要考虑什么时候使用箭头函数。即应用场景
.临时使用的函数,并不会刻意的去调用
1.异步的处理函数
2.事件的处理
2.继续去沿用外层的this
3.对象的属性不要去用箭头函数,除非是特别的需求
4.数组方法的时候,保证代码的简洁


		const arr = [1,2,89,45,123,54];

		const result = arr.map(num => num*2);
		console.log(result)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值