ES6——函数进阶2-箭头函数

1.箭头函数
解决问题:
1.缩减代码
2.改变 this 指向

箭头函数基本形式

//普通写法
    const number=function(number){
        return number*2
    };

    //箭头函数
    const number2=(number)=>{
        return number*2
    };

    console.log(number2(2)) //-->4
let func = (num) => num;
let func = () => num;
let sum = (num1,num2) => num1 + num2;
[1,2,3].map(x => x * x);
在这里插入代码片

2. 箭头函数基本特点

(1). 箭头函数this为父作用域的this,不是调用时的this

箭头函数的this永远指向其父作用域,任何方法都改变不了,包括call,apply,bind。
普通函数的this指向调用它的那个对象。

let person = {
    name:'jike',
    init:function(){
        //为body添加一个点击事件,看看这个点击后的this属性有什么不同
        document.body.onclick = ()=>{
            alert(this.name);//?? this在浏览器默认是调用时的对象,可变的?                  
        }
    }
}
person.init();

其中,init是function,以person.init调用,其内部this就是person本身,而onclick回调是箭头函数,
其内部的this,就是父作用域的this,就是person,能得到name。
(2). 箭头函数不能作为构造函数,不能使用new

//构造函数如下:
function Person(p){
    this.name = p.name;
}
//如果用箭头函数作为构造函数,则如下
var Person = (p) => {
    this.name = p.name;
}

由于this必须是对象实例,而箭头函数是没有实例的,此处的this指向别处,不能产生person实例,矛盾。
(3). 箭头函数没有arguments,caller,callee

let B = (b)=>{
  console.log(arguments);
}
B(2,92,32,32);   // Uncaught ReferenceError: arguments is not defined

let C = (...c) => {
  console.log(c);
}
C(3,82,32,11323);  // [3, 82, 32, 11323]

(4). 箭头函数通过call和apply调用,不会改变this指向,只会传入参数

let obj2 = {
    a: 10,
    b: function(n) {
        let f = (n) => n + this.a;
        return f(n);
    },
    c: function(n) {
        let f = (n) => n + this.a;
        let m = {
            a: 20
        };
        return f.call(m,n);
    }
};
console.log(obj2.b(1));  // 11
console.log(obj2.c(1)); // 11

(5). 箭头函数没有原型属性

var a = ()=>{
  return 1;
}

function b(){
  return 2;
}

console.log(a.prototype);  // undefined
console.log(b.prototype);   // {constructor: ƒ}

(6). 箭头函数不能作为Generator函数,不能使用yield关键字

(7). 箭头函数返回对象时,要加一个小括号

var func = () => ({ foo: 1 }); //正确
var func = () => { foo: 1 };   //错误

(8). 箭头函数在ES6 class中声明的方法为实例方法,不是原型方法


class Super{
    sayName(){
        //do some thing here
    }
}
//通过Super.prototype可以访问到sayName方法,这种形式定义的方法,都是定义在prototype上
var a = new Super()
var b = new Super()
a.sayName === b.sayName //true
//所有实例化之后的对象共享prototypy上的sayName方法


//demo2
class Super{
    sayName =()=>{
        //do some thing here
    }
}
//通过Super.prototype访问不到sayName方法,该方法没有定义在prototype上
var a = new Super()
var b = new Super()
a.sayName === b.sayName //false
//实例化之后的对象各自拥有自己的sayName方法,比demo1需要更多的内存空间

因此,在class中尽量少用箭头函数声明方法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值