ES6新增箭头函数 () => {}
箭头函数的简写形式
// 1.箭头函数不能直接存在,它等同于无名函数,一般用来作为值得存在
var fn = () => {
console.log("hello")
}
fn()
//语义化太差,伤害代码的可读性。
// 2.最简化写法:省略小括号,花括号,和return
// 注:这里要只有一个参数,是一个简单的语句,且有返回值的时候
var fn = a=>a<10 ? "0"+a : a;
var num = fn(6)
console.log(num)
// 相当于下面的代码
function fn(a){
if(a < 10){
return "0"+a;
}else{
return "a";
}
}
// 3.这里如果使用最简化写法,返回的是一个对象,需要将对象使用小括号包裹
var fn = (a)=>({name: a});
var str = fn("哈哈").name
console.log(str)
// 4.只要花括号没有省略,想要有返回值,必须要加一个return,一个以上的参数时,小括号不能省略
var fn = (a, b) => { return {
name: a,
age: b
}}
var str = fn("哈哈", 18).age
console.log(str)
// 箭头函数中的this
var obj = {
age: 19,
say: function() {
setTimeout(function() {
console.log(this, this.age); // window undefined
}, 0);
},
}
obj.say()
var obj1 = {
age: 19,
say: function() {
setTimeout(() => {
console.log(this, this.age); // obj1 19
}, 0);
}
};
obj1.say()
// 箭头函数看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别。
// 箭头函数内部的this是由上下文确定的。箭头函数的this总是指向外层调用者obj。
// 这里可以看出箭头函数中访问的this实际上是其父级作用域中的this,
// 箭头函数本身的this是不存在的,所以箭头函数不能作为构造函数
// 5. 箭头函数通过call和apply调用,不会改变this指向,只会传入参数复制代码
let obj = {
num: 10,
fn: function(n) {
let f1 = (n) => n + this.num;
return f1(n);
},
fun: function(n) {
let f2 = (n) => n + this.num;
let m = {
num: 20
};
return f2.call(m,n);
}
};
console.log(obj.fn(1)); // 11
console.log(obj.fun(1)); // 11
// 6. 箭头函数在ES6 class中声明的方法为实例方法,不是原型方法
// deom1
class Super1{
sayName(){
console.log("哈哈")
}
}
console.log(Super1.prototype)
// //通过Super.prototype可以访问到sayName方法,这种形式定义的方法,都是定义在prototype上
var a = new Super1()
var b = new Super1()
a.sayName === b.sayName //true
// // //所有实例化之后的对象共享prototypy上的sayName方法
//demo2
class Super2{
sayName =()=>{
console.log("嘻嘻")
}
}
console.log(Super2.prototype)
// //通过Super.prototype访问不到sayName方法,该方法没有定义在prototype上
var a = new Super2()
var b = new Super2()
a.sayName === b.sayName //false
//实例化之后的对象各自拥有自己的sayName方法,比demo1需要更多的内存空间
// 7.多重箭头函数就是一个高阶函数,相当于内嵌函数
const add = x => y => y + x;
console.log( add(1)(2) )
//相当于
function add(x){
return function(y){
return y + x;
};
}
console.log( add(1)(2) )
// 8.箭头函数也可以使用闭包:
// 标准的闭包函数
function fn(){
var i=0;
return function b(){
return (++i);
};
};
var v=fn();
v(); //1
v(); //2
// //箭头函数体的闭包( i=0 是默认参数)
var Add = (i=0) => {return (() => (++i) )};
var v = Add();
v(); //1
v(); //2
// //因为仅有一个返回,return 及括号()也可以省略
var Add = (i=0)=> ()=> (++i);
箭头函数是适用的场景
// 箭头函数不适用的场景(或者不建议使用的场景)
// 1.作为对象的属性
var obj = {
a: 1,
b: () => {
console.log(this.a); // undefined
}
};
obj.b()
// 2.构造函数,因为箭头函数中的this指向外层
// 3.作为原型方法
function Person(name) {
this.name = name;
}
Person.prototype.say = function() {
console.log(this); // 指向实例
};
Person.prototype.show = () => {
console.log(this); // window
};
var pe = new Person('Jack');
pe.say(); // {name: 'Jack'}
pe.show(); // window