【 ES6 】箭头函数

箭头函数

( ) => { }
缩减代码

const add = function (number) {
    return number + 1
}

// 箭头函数
// 单个参数 可以不加 () 直接返回数据 可以不加return
const add = number => number + 1;
// 多参数 需要加()
const add = (number,num) => number + num;

console.log(add(20));

此时会报错 this指向问题会出错

const team = {
    members: ['Henry', 'Bucky', 'Taylor'],
    teamName: 'ES6',
    teamSummary: function () {
        return this.members.map(function (member) {
            // this指向出错了
            return `${member} 隶属于 ${this.teamName}`
        })
    }
}
console.log(team.teamSummary());
/*
[
    'Henry 隶属于 undefined',
    'Bucky 隶属于 undefined',
    'Taylor 隶属于 undefined'
]
*/

解决上方this指向报错问题

const team = {
    members: ['Henry', 'Bucky', 'Taylor'],
    teamName: 'ES6',
    teamSummary: function () {
        // 提前将this保存起来
        let selt = this
        return this.members.map(function (member) {
            // this指向出错了
            return `${member} 隶属于 ${selt.teamName}`
        })
    }
}
console.log(team.teamSummary());
// [ 'Henry 隶属于 ES6', 'Bucky 隶属于 ES6', 'Taylor 隶属于 ES6' ]
const team = {
    members: ['Henry', 'Bucky', 'Taylor'],
    teamName: 'ES6',
    teamSummary: function () {
        return this.members.map(function (member) {
            // this指向出错了
            return `${member} 隶属于 ${this.teamName}`
        }.bind(this))
        // 使用bind改变this指向问题
    }
}
console.log(team.teamSummary());
// [ 'Henry 隶属于 ES6', 'Bucky 隶属于 ES6', 'Taylor 隶属于 ES6' ]

改变this指向

const team = {
    members: ['Henry', 'Bucky', 'Taylor'],
    teamName: 'ES6',
    teamSummary: function () {
    // 箭头函数
        return this.members.map((member) => {
            // this指向team对象
            return `${member} 隶属于 ${this.teamName}`
        })
    }
}
console.log(team.teamSummary());
// [ 'Henry 隶属于 ES6', 'Bucky 隶属于 ES6', 'Taylor 隶属于 ES6' ]

this是静态的 this始终指向函数声明时所在作用域下的this的值

		window.name = 'zwj'
        const people = {
        	name:"LiSi"
        }

		let getOne = function(){
        	console.log(this.name)           
		}
		

        let getTwo = ()=>{
        	console.log(this.name)
        }
        // 直接调用 this 指向window
        getOne() // zwj
        getTwo() // zwj

        // call 改变this指向
        getOne.call(people) // LiSi
        getTwo.call(people) // zwj

不能作为构造函数实例化对象

        let People = (name,age)=>{
        	this.name = name
        	this.age = age
        }
        let me =new People('zwjs',25)
        console.log(me)
        //  TypeError: People is not a constructor

不能使用arguments对象

        var fn = ()=>{
        	console.log(arguments)
        }
        fn(1,2,3,4,5) 
        // Uncaught ReferenceError: arguments is not defined
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值