JS ES6 箭头函数
根据网上的各种介绍,然后加我自己的一些理解,总结的,有错误请多多谅解
一、基本用法
1.箭头函数只能用赋值式写法,不能用声明式写法
let a = () => {
console.log('hehe');
}
a();
2.如果参数只有一个,可以不加括号,如果没有或者参数多于一个就要加括号
let a = uName => console.log('hehe'); //一个参数
let b = () => {console.log('hehe');} //无参数
let c = (uAge,uName) => {console.log('hehe');} //两个参数
3.如果函数体只有一句话,可以不加花括号
let a = uName => console.log('hehe'); //只有一句话
4.如果函数体没有花括号,可以不写return,箭头函数会帮你return(函数体的花括号与return关键字一起出现)
const add = (p1, p2) => p1 + p2
console.log(add(1,3));
6.箭头函数没有自己的this,this继承自外围作用域,也就是说和外层作用域的this保持一致
箭头函数没有自己的
this
,而是一层一层的向上级作用域查找,直到有this
。总是指向定义时所在的对象,而不是运行时所在的对象。
箭头函数是没有
this
的,在箭头函数里使用this
就像使用普通变量一样,在箭头函数的scope
内找不到,都会一直向父scope
寻找。在使用感觉上可以说是等同于之前经常写的
var self = this;
这句。即:书写箭头函数时的那块代码外面的 this 。
7.用call()
或apply()
方法调用一个箭头函数时,只能传递参数,不能绑定this
也就是说
call()
的第一个参数会被忽略
obj1 = {
ttype : '年龄',
};
let a = num => {
console.log(this.ttype+':'+num*2);
};
let b = function(num){
console.log(this.ttype+':'+num*2);
};
a.call(obj1,65); //箭头函数 undefined:130
b.call(obj1,30); //年龄:60
8.箭头函数没有prototype
属性
let Foo = () => {};
console.log(Foo.prototype); // undefined
9.箭头函数在参数和箭头之间不能换行
let func = ()
=> 1;
// SyntaxError: expected expression, got '=>'
二、不能用箭头函数的地方
1.定义对象的方法时,不能用箭头函数
箭头函数不能作为方法
let a = {
num : 1,
getNum : () => console.log(this.num),
};
a.getNum(); //undefined
箭头函数本身没this
,所以往上一层,因为对象a
不能构成一个作用域,所以再往上达到全局作用域
2.在原型对象上定义函数时,不能用箭头函数
function Person(uName) {
this.name = uName;
} //定义一个原型对象
Person.prototype.sayName = () => {
console.log(this.name);
}; //用箭头函数在原型对象上添加一个方法
let P1 = new Person('Blackn');
P1.sayName() //undefined
sayName
方法的this
也是指向了外层作用域,也就是window
3.在dom元素上绑定监听事件
let button = document.getElementById('myButton');
button.addEventListener('click',() => {
console.log(this) //window
this.innerHtml = 'Clicked Button';
});
这里的this
指向window
,因为他的外层就直接是window
了,不是指向myButton
按钮
当this
是由目标对象决定时我们不能用箭头函数
4.构造函数(在ES6中引入了类的概念)不能用箭头函数
箭头函数不能用作构造器,和
new
一起用会抛出错误。
let Person = (uAge) => {
this.uname = 'Blackn';
this.age = uAge;
}
let P1 = new Person('21'); //TypeError: Person is not a constructor
因为箭头函数没有this
所以不能用作构造函数,构造函数一般需要使用this.xxx = xxx
,